如何在保留订单并就地更新的同时使列表仅包含唯一项目?我知道可以使用一套,但它不能保证订购。
3 回答

森林海
TA贡献2011条经验 获得超2个赞
使用支持集和 while 循环:
def unique(arr):
tmp_set = set()
i = 0
while i < len(arr):
if arr[i] in tmp_set:
del arr[i]
else:
tmp_set.add(arr[i])
i += 1
以上将就地更新数组,并保留元素的顺序。

鸿蒙传说
TA贡献1865条经验 获得超7个赞
增强的 CodeSpeed 解决方案。
lst = [1, 2, 2, 1, 1]
seen = set()
length = len(lst) - 1
i = 0
while i < length:
if lst[i] in seen:
del lst[i]
i -= 1
seen.add(lst[i])
i += 1
length = len(lst)
print(lst)
添加回答
举报
0/150
提交
取消