簡體   English   中英

比較不同List python中兩個元組的項

[英]Compare items of two tuples in different List python

你好朋友我需要你的幫助。 我想在兩個元組列表之間進行比較,如果兩個元組之間有多個相同的值,我打印這個結果 exp:

L1 = [('G', 'T'), ('T', 'T'), ('T', 'U'), ('U', 'I'), ('I', 'P')]
L2 = [('E', 'G'), ('G', 'T'), ('T', 'P')]

output:[0,1]

使用列表理解:

L1 = [('G', 'T'), ('T', 'T'), ('T', 'U'), ('U', 'I'), ('I', 'P')]
L2 = [('E', 'G'), ('G', 'T'), ('T', 'P')]

indices = [[L1.index(s),i] for i, s in enumerate(L2) if s in L1]

# print the first match (in this case there is only one match)
print(indices[0])
[0, 1]

[[L1.index(s),i] for i, s in enumerate(L2) if s in L1]解釋:

  • for i, s in enumerate(L2) : i 是索引,s 在 L2 的元組元素中
  • if s in L1 :檢查當前s是否也在 L1 中
  • [L1.index(s),i] :返回索引列表

PS:對於重復項,這可能表現不佳。

這是一個更動態的解決方案。 我稍微改變了你的輸入以獲得不同的測試用例。 這將適用於重復,也適用於 O(N) 時間。

from collections import defaultdict
L1 = [('G', 'T'), ('T', 'T'), ('T', 'U'), ('U', 'I'), ('I', 'P'), ('U', 'I')]
L2 = [('E', 'G'), ('G', 'T'), ('T', 'P'), ('U', 'I')]
S1 = defaultdict(list)
S2 = defaultdict(list)
for indx, element in enumerate(L1):
    S1[element].append(indx)
for indx, element in enumerate(L2):
    S2[element].append(indx)

duplicate_elements = set(S1).intersection(set(S2))
print("Mutual elements:", *[(S1[dup], S2[dup]) for dup in duplicate_elements])

Output:

Mutual elements: ([0], [1]) ([3, 5], [3])

暫無
暫無

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

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