Checking if a list has duplicate lists(检查列表是否有重复列表)
问题描述
给定一个列表列表,我想确保没有两个列表具有相同的值和顺序.例如 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))
这篇关于检查列表是否有重复列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查列表是否有重复列表


- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 沿轴计算直方图 2022-01-01