简体   繁体   English

比较不同List python中两个元组的项

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

Hello freinds i need your help.你好朋友我需要你的帮助。 I want to compare between two lists of tuples,if there is more than one identical value between the two tuples I print this result exp:我想在两个元组列表之间进行比较,如果两个元组之间有多个相同的值,我打印这个结果 exp:

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

output: [0,1] output:[0,1]

Use list comprehension:使用列表理解:

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]

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

  • for i, s in enumerate(L2) : i is the index, s in the tuple element of L2 for i, s in enumerate(L2) : i 是索引,s 在 L2 的元组元素中
  • if s in L1 : this checks if the current s is also in L1 if s in L1 :检查当前s是否也在 L1 中
  • [L1.index(s),i] : this returns a list of the index [L1.index(s),i] :返回索引列表

PS: For duplicates this may not behave well. PS:对于重复项,这可能表现不佳。

Here is a little more dynamic of a solution.这是一个更动态的解决方案。 I altered your input a little to get a different test case.我稍微改变了你的输入以获得不同的测试用例。 This will work for duplicates and also works in O(N) time.这将适用于重复,也适用于 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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM