簡體   English   中英

比較列表中的元組元素

[英]comparing elements of tuples in a list

我正在嘗試編寫一個比較每個元組的第二個元素並提取包含第二個元素重復項的元組的代碼。

例如,如果我有

List = [(0, 2), (1, 0), (2, 1), (3, 2)]

duplicate_tuples = [(0, 2), (3, 2)]  # desired output

我只是不知道如何在我的迭代中指定第二個元素

for i in List: # would iterate each tuple
    if i[1] of i in List is duplicate...

缺乏Python語法令人沮喪。 我應該如何解決這個問題?

您可以在collections.defaultdict()收集元組,然后報告具有多個重復項的列表:

from collections import defaultdict

lst = [(0, 2), (1, 0), (2, 1), (3, 2), (2, 0)]

dups = defaultdict(list)
for fst, snd in lst:
   dups[snd].append((fst, snd))

print([v for k, v in dups.items() if len(v) > 1])
# [[(0, 2), (3, 2)], [(1, 0), (2, 0)]]

或者將重復項保留在字典中以便於查找:

print({k: v for k, v in dups.items() if len(v) > 1})
# {2: [(0, 2), (3, 2)], 0: [(1, 0), (2, 0)]}

在numpy數組中工作將比列表/元組有效。

import numpy as np
a = np.array([(0, 2), (1, 0), (2, 1), (3, 2),(3,0)])

unique_vals,inverse_indices,counts=np.unique(a[:,1],return_inverse=True,return_counts=True)

根據唯一函數的輸出,我們可以生成重復列表

duplicates=[(i,a[inverse_indices==i]) for i  in unique_vals[np.where(counts>1)[0]]]

輸出:

[(0, array([[1, 0],[3, 0]])),
 (2, array([[0, 2],[3, 2]]))]

可能會有更多重復項,因此groupby是更好的選擇。

In [6]: from itertools import groupby
In [7]: for g,l in groupby(sorted(lst,key=lambda x:x[1]),key=lambda x:x[1]):
   ...:     temp = list(l)
   ...:     if len(temp) > 1:
   ...:         print g,temp
   ...:   
2 [(0, 2), (3, 2)]

這是使用numpy的另一種方法:

duplicate_list = []

foo = np.array([(0,2), (1,0), (2,1), (3,2), (3,0), (1,2)])

for i in range(len(np.unique(foo[:,1]))):
    if np.sum(foo[:,1] == i) > 1:
        duplicate_list.append(foo[foo[:,1] == i].tolist())

print(duplicate_list)

輸出:

[[[1, 0], [3, 0]], [[0, 2], [3, 2], [1, 2]]]

使用np.unique(foo [:,1])我們獲得一個元組中第二個元素的唯一元素,然后如果計數大於1或存在重復項,則將其追加到列表中,這將返回2個列表我們有2次出現(0和2)。 如果您有特定的數字,請說(2),那么我們可以避免循環。

例如

bla = np.array([(0, 2), (1, 0), (2, 1), (3, 2)])
duplicate = []

if np.sum(bla[:,1] == 2) > 1:
    duplicate = bla[bla[:,1] == 2].tolist()

print(duplicate)

輸出:

[[0, 2], [3, 2]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM