繁体   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