我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
减少变量与顺序保存:
假设我们有一个列表:
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]
其他回答
与回复中列出的其他解决方案相比,下面是最快的python解决方案。
使用短路计算的实现细节允许使用列表理解,这足够快。visit .add(item)总是返回None作为结果,它被赋值为False,所以or的右边总是这样的表达式的结果。
自己计时
def deduplicate(sequence):
visited = set()
adder = visited.add # get rid of qualification overhead
out = [adder(item) or item for item in sequence if item not in visited]
return out
我没有看到非哈希值的答案,一行,nlog n,标准库,所以这是我的答案:
list(map(operator.itemgetter(0), itertools.groupby(sorted(items))))
或作为一个生成函数:
def unique(items: Iterable[T]) -> Iterable[T]:
"""For unhashable items (can't use set to unique) with a partial order"""
yield from map(operator.itemgetter(0), itertools.groupby(sorted(items)))
可以使用Python set或dict.fromkeys()方法删除重复项。 dict.fromkeys()方法将一个列表转换为一个字典。字典不能包含重复的值,因此dict.fromkeys()将返回只有唯一值的字典。 集,像字典一样,不能包含重复的值。如果将列表转换为集合,则删除所有重复项。
方法一:幼稚法
mylist = [5, 10, 15, 20, 3, 15, 25, 20, 30, 10, 100]
uniques = []
for i in mylist:
if i not in uniques:
uniques.append(i)
print(uniques)
方法二:使用set()
mylist = [5, 10, 15, 20, 3, 15, 25, 20, 30, 10, 100]
myset = set(mylist)
print(list(myset))
这里有一个例子,返回没有重复的列表,保持顺序。不需要任何外部导入。
def GetListWithoutRepetitions(loInput):
# return list, consisting of elements of list/tuple loInput, without repetitions.
# Example: GetListWithoutRepetitions([None,None,1,1,2,2,3,3,3])
# Returns: [None, 1, 2, 3]
if loInput==[]:
return []
loOutput = []
if loInput[0] is None:
oGroupElement=1
else: # loInput[0]<>None
oGroupElement=None
for oElement in loInput:
if oElement<>oGroupElement:
loOutput.append(oElement)
oGroupElement = oElement
return loOutput
我用纯python函数做到了这一点。当您的项目值是JSON时,这是有效的。
[i for n, i in enumerate(items) if i not in items[n + 1 :]]