問題描述
給定一個列表列表,我想確保沒有兩個列表具有相同的值和順序.例如 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))
這篇關于檢查列表是否有重復列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!