在保留订单并就地更新列表的同时,如何使列表仅包含唯一项?
我知道可以使用一组,但不能保证订购。
答案 0 :(得分:0)
使用支持集,并进行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
上面的代码将就地更新数组,并保留元素的顺序。
答案 1 :(得分:-1)
增强的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)
答案 2 :(得分:-1)
仅当新loop
中不存在这些条目时,才可以使用list
遍历列表中的条目并将它们插入新的list
中。 / p>
lst = [3,3,3,1,2,2,4]
my_list = []
for i in lst:
if i not in my_list:
my_list.append(i)
my_list
# Output - [3, 1, 2, 4]
我希望这会有所帮助。