检查列表是否有重复的列表


问题内容

给定一个列表列表,我要确保没有两个具有相同值和顺序的列表。例如,my_list = [[1, 2, 4, 6, 10], [12, 33, 81, 95, 110], [1, 2, 4, 6, 10]]它应该返回重复列表,即存在[1, 2, 4, 6, 10]

我曾经使用过,while但是它并不能按我的意愿工作。有人知道如何修复代码:

routes = [[1, 2, 4, 6, 10], [1, 3, 8, 9, 10], [1, 2, 4, 6, 10]]
r = len(routes) - 1
i = 0
while r != 0:
    if cmp(routes[i], routes[i + 1]) == 0:
        print "Yes, they are duplicate lists!"
    r -= 1
    i += 1

问题答案:

您可以计算列表推导中的出现次数,将其转换为,tuple以便可以哈希并应用唯一性:

routes = [[1, 2, 4, 6, 10], [1, 3, 8, 9, 10], [1, 2, 4, 6, 10]]
dups = {tuple(x) for x in routes if routes.count(x)>1}

print(dups)

结果:

{(1, 2, 4, 6, 10)}

足够简单,但是由于重复调用,导致很多循环在后台进行count。还有另一种方式,涉及散列,但是复杂度较低,可以使用collections.Counter

from collections import Counter

routes = [[1, 2, 4, 6, 10], [1, 3, 8, 9, 10], [1, 2, 4, 6, 10]]

c = Counter(map(tuple,routes))
dups = [k for k,v in c.items() if v>1]

print(dups)

结果:

[(1, 2, 4, 6, 10)]

(只计算元组转换的子列表-解决哈希问题-,然后使用列表推导生成重复列表,仅保留出现多次的项目)

现在,如果您只想检测出某些重复列表(不打印它们),则可以

  • 将列表列表转换为元组列表,以便您可以将它们散列到一组中
  • 比较列表的长度与集合的长度:

如果有重复项,则len不同:

routes_tuple = [tuple(x) for x in routes]    
print(len(routes_tuple)!=len(set(routes_tuple)))

或者,map很少能够在Python 3中使用它,因此:

print(len(set(map(tuple,routes))) != len(routes))