![](/img/trans.png)
[英]Python - How to find and merge duplicates in list of addresses (which are lists themselves)
[英]How to find duplicates of list of arbitrary sized lists in < n^2 time in python?
如何在python中的<n ^ 2列表中找到重復項? 我不能使用字典在線性時間內完成它,就像我使用所有標准類型一樣。 我只能想到以下解決方案:
arr = [[1,2], [1,2,4], [1,2], [5,6], [8], [8]]
unique_arr = []
dups = []
for item in arr:
for item2 in unique_arr:
if (item == item2).all():
dups.append(item)
continue
unique_arr.append(item)
dups
預期結果是[[1,2], [8]]
謝謝
collections.Counter
一個可能的解決方案:
arr = [[1,2], [1,2,4], [1,2], [5,6], [8], [8]]
from collections import Counter
print([[*i] for i,c in Counter(map(tuple, arr)).items() if c > 1])
打印:
[[1, 2], [8]]
要么:
版本與itertools.groupby
並sorted
:
from itertools import groupby
print([v for v, g in groupby(sorted(arr, key=len)) if any(i > 0 for i, _ in enumerate(g))])
打印:
[[8], [1, 2]]
我不明白為什么你需要遍歷內部列表...你可以簡單地迭代外部列表。
arr = [[1,2], [1,2,4], [1,2], [5,6], [8], [8]]
unique_arr = []
dups = []
for item in arr:
if item not in unique_arr:
unique_arr.append(item)
else:
unique_arr.append(item)
這里還有一個解決方案:
arr = [[1,2], [1,2,4], [1,2], [5,6], [8], [8]]
dic = {}
dups = []
for ele in arr:
try:
if dic[str(ele)] is 1:
dups.append(ele)
except:
dic[str(ele)] = 1
print(dups)
輸出:
[[1, 2], [8]]
雖然您不能將列表用作字典鍵,但您可以使用元組。
arr = [[1,2], [1,2,4], [1,2], [5,6], [8], [8]]
dups = []
found = set()
for item in arr:
tup = tuple(item)
if tup in found:
dups.append(list(tup))
found.add(tup)
print(dups)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.