我正在尝试查找list1中的任何子列表是否有重复的值,因此我需要知道list1中的数字是否与列表1中的数字相同
数字代表和弦,list1中每一项的和弦不能重叠,如果它们重叠,那么我有一个模块,它会重新运行一个新的list1,直到没有一个和弦是smae
请帮帮忙
list1 = [[7, 20], [20, 31, 32], [66, 67, 68],[7, 8, 9, 2],
[83, 84, 20, 86, 87], [144, 145, 146, 147, 148, 149]]
x=0
while x != 169:
if list1.count(x) > 0:
print ("repeat found")
else:
print ("no repeat found")
x+=1发布于 2013-06-09 06:28:44
不如这样吧:
is_dup = sum(1 for l in list1 if len(set(l)) < len(l))
if is_dup > 0:
print ("repeat found")
else:
print ("no repeat found")使用any的另一个示例
any(len(set(l)) < len(l) for l in list1)为了检查所有列表中是否只有一项重复,我会将它们链接起来并进行检查。将列表扁平化归功于。
flattened = sum(list1, [])
if len(flattened) > len(set(flattened)):
print ("dups")
else:
print ("no dups")我想扁平化列表的正确方法是使用itertools.chain,它可以这样使用:
flattened = list(itertools.chain(*list1))这可以替换我上面使用的sum调用,如果这看起来像是黑客的话。
发布于 2013-06-09 06:29:56
更新后的问题的解决方案
def has_duplicates(iterable):
"""Searching for duplicates in sub iterables.
This approach can be faster than whole-container solutions
with flattening if duplicates in large iterables are found
early.
"""
seen = set()
for sub_list in iterable:
for item in sub_list:
if item in seen:
return True
seen.add(item)
return False
>>> has_duplicates(list1)
True
>>> has_duplicates([[1, 2], [4, 5]])
False
>>> has_duplicates([[1, 2], [4, 5, 1]])
True在集合中查找速度很快。如果你想让seen更快,就不要使用list。
问题的原始版本的解决方案
如果列表的长度大于由此列表组成的集合的长度,则必须有重复的项目,因为集合只能有唯一的元素:
>>> L = [[1, 1, 2], [1, 2, 3], [4, 4, 4]]
>>> [len(item) - len(set(item)) for item in L]
[1, 0, 2]这是这里的关键
>>> {1, 2, 3, 1, 2, 1}
set([1, 2, 3])编辑
如果您对每个子列表的重复次数不感兴趣。这样效率会更高,因为它会在第一个大于0的数字后停止
>>> any(len(item) - len(set(item)) for item in L)
True感谢@mata指出这一点。
发布于 2013-06-09 06:36:06
from collections import Counter
list1=[[7, 20], [20, 31, 32], [66, 67, 68],
[7, 8, 9, 2], [83, 84, 20, 86, 87],
[144,144, 145, 146, 147, 148, 149]]
for i,l in enumerate(list1):
for r in [x for x,y in Counter(x for x in l).items() if y > 1]:
print 'at list ', i, ' item ', r , ' repeats'这里给出了全局重复值:
expl=sorted([x for l in list1 for x in l])
print [x for x,y in zip(expl, expl[1:]) if x==y]https://stackoverflow.com/questions/17004469
复制相似问题