我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?


当前回答

使用set,但保持顺序

unique = set()
[unique.add(n) or n for n in l if n not in unique]

其他回答

检查字符串'a'和'b'

clean_list = []
    for ele in raw_list:
        if 'b' in ele or 'a' in ele:
            pass
        else:
            clean_list.append(ele)
Test = [1,8,2,7,3,4,5,1,2,3,6]
Test.sort()
i=1
while i< len(Test):
  if Test[i] == Test[i-1]:
    Test.remove(Test[i])
  i= i+1
print(Test)

为了完整起见,由于这是一个非常流行的问题,toolz库提供了一个独特的函数:

>>> tuple(unique((1, 2, 3)))
(1, 2, 3)
>>> tuple(unique((1, 2, 1, 3)))
(1, 2, 3)

不使用set

data=[1, 2, 3, 1, 2, 5, 6, 7, 8]
uni_data=[]
for dat in data:
    if dat not in uni_data:
        uni_data.append(dat)

print(uni_data) 

这个人关心的是没有太多麻烦的订单(OrderdDict & others)。可能不是最python化的方式,也不是最短的方式,但却达到了目的:

def remove_duplicates(item_list):
    ''' Removes duplicate items from a list '''
    singles_list = []
    for element in item_list:
        if element not in singles_list:
            singles_list.append(element)
    return singles_list