我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
不使用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)
其他回答
下面的代码是简单的删除重复列表
def remove_duplicates(x):
a = []
for i in x:
if i not in a:
a.append(i)
return a
print remove_duplicates([1,2,2,3,3,4])
它返回[1,2,3,4]
检查字符串'a'和'b'
clean_list = []
for ele in raw_list:
if 'b' in ele or 'a' in ele:
pass
else:
clean_list.append(ele)
简单易行:
myList = [1, 2, 3, 1, 2, 5, 6, 7, 8]
cleanlist = []
[cleanlist.append(x) for x in myList if x not in cleanlist]
输出:
>>> cleanlist
[1, 2, 3, 5, 6, 7, 8]
有时你需要删除重复的项目,而不需要创建新的列表。例如,列表很大,或者将其作为影子副本保存
from collections import Counter
cntDict = Counter(t)
for item,cnt in cntDict.items():
for _ in range(cnt-1):
t.remove(item)
不使用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)