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))
这篇关于检查列表是否有重复列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查列表是否有重复列表
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
