检查列表是否有重复的列表 [英] Checking if a list has duplicate lists

查看:57
本文介绍了检查列表是否有重复的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个列表列表,我要确保没有两个具有相同值和顺序的列表.例如,使用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会有所不同:

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))

这篇关于检查列表是否有重复的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆