Py学习  »  Python

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

Mohamed • 5 年前 • 1429 次点击  

你好,弗林兹,我需要你的帮助。 我想比较两个元组列表,如果两个元组之间有多个相同的值,我将打印此结果 经验:

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

输出: [0,1]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49857
 
1429 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Error - Syntactical Remorse
Reply   •   1 楼
Error - Syntactical Remorse    5 年前

这里有一个更具活力的解决方案。为了得到一个不同的测试用例,我稍微修改了你的输入。这对副本有效,而且在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])

输出:

Mutual elements: ([0], [1]) ([3, 5], [3])
makis
Reply   •   2 楼
makis    5 年前

使用列表理解:

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是二级元组元素中的索引
  • if s in L1 :这将检查当前 s 也在L1
  • [L1.index(s),i] :返回索引列表

附言:对于复制品,这可能表现不好。