我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
我用纯python函数做到了这一点。当您的项目值是JSON时,这是有效的。
[i for n, i in enumerate(items) if i not in items[n + 1 :]]
其他回答
Write a Python program to create a list of numbers by taking input from the user and then remove the duplicates from the list. You can take input of non-zero numbers, with an appropriate prompt, from the user until the user enters a zero to create the list assuming that the numbers are non-zero.
Sample Input: [10, 34, 18, 10, 12, 34, 18, 20, 25, 20]
Output: [10, 34, 18, 12, 20, 25]
lst = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER LIST ELEMENTS :: ")
while True:
n = int(input())
if n == 0 :
print("!!!!!!!!!!! EXIT !!!!!!!!!!!!")
break
else :
lst.append(n)
print("LIST ELEMENR ARE :: ",lst)
#dup = set()
uniq = []
for x in lst:
if x not in uniq:
uniq.append(x)
# dup.add(x)
print("UNIQUE ELEMENTS IN LIST ARE :: ",uniq)
您可以使用以下函数:
def rem_dupes(dup_list):
yooneeks = []
for elem in dup_list:
if elem not in yooneeks:
yooneeks.append(elem)
return yooneeks
例子:
my_list = ['this','is','a','list','with','dupicates','in', 'the', 'list']
用法:
rem_dupes(my_list)
[‘这个’,‘是’,‘“,“列表”,“与”,“dupicates”,“在”,“的”)
减少变量与顺序保存:
假设我们有一个列表:
l = [5, 6, 6, 1, 1, 2, 2, 3, 4]
减少变体(无效):
>>> reduce(lambda r, v: v in r and r or r + [v], l, [])
[5, 6, 1, 2, 3, 4]
5倍快,但更复杂
>>> reduce(lambda r, v: v in r[1] and r or (r[0].append(v) or r[1].add(v)) or r, l, ([], set()))[0]
[5, 6, 1, 2, 3, 4]
解释:
default = (list(), set())
# user list to keep order
# use set to make lookup faster
def reducer(result, item):
if item not in result[1]:
result[0].append(item)
result[1].add(item)
return result
reduce(reducer, l, default)[0]
尝试使用集合:
import sets
t = sets.Set(['a', 'b', 'c', 'd'])
t1 = sets.Set(['a', 'b', 'c'])
print t | t1
print t - t1
使用set,但保持顺序
unique = set()
[unique.add(n) or n for n in l if n not in unique]