检查列表是否有重复列表
问题描述
给定一个列表列表,我想确保没有两个列表具有相同的值和顺序.例如 my_list = [[1, 2, 4, 6, 10], [12, 33, 81, 95, 110], [1, 2, 4, 6, 10]]
应该返回我是否存在重复列表,即 [1, 2, 4, 6, 10]
.
Given a list of lists, I want to make sure that there are no two lists that have the same values and order. For instance with my_list = [[1, 2, 4, 6, 10], [12, 33, 81, 95, 110], [1, 2, 4, 6, 10]]
it is supposed to return me the existence of duplicate lists, i.e. [1, 2, 4, 6, 10]
.
我使用了 while
但它没有按我的意愿工作.有人知道如何修复代码:
I used while
but it doesn't work as I want. Does someone know how to fix the code:
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
以便你可以散列 &应用唯一性:
you could count the occurrences in a list comprehension, converting them to a tuple
so you can hash & apply unicity:
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
:
Simple enough, but a lot of looping under the hood because of repeated calls to count
. There's another way, which involves hashing but has a lower complexity would be to use 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)]
(只需计算元组转换的子列表 - 修复哈希问题 - 并使用列表理解生成 dup 列表,只保留出现多次的项目)
(Just count the tuple-converted sublists - fixing the hashing issue -, and generate dup list using list comprehension, keeping only items which appear more than once)
现在,如果你只是想检测有一些重复的列表(不打印它们),你可以
Now, if you just want to detect that there are some duplicate lists (without printing them) you could
- 将列表列表转换为元组列表,以便您可以在集合中散列它们
- 比较列表的长度和集合的长度:
如果有一些重复,len 是不同的:
len is different if there are some duplicates:
routes_tuple = [tuple(x) for x in routes]
print(len(routes_tuple)!=len(set(routes_tuple)))
或者,能够在 Python 3 中使用 map
的情况非常少见,因此值得一提:
or, being able to use map
in Python 3 is rare enough to be mentionned so:
print(len(set(map(tuple,routes))) != len(routes))
相关文章