首页 > 解决方案 > 比较不同List python中两个元组的项目

问题描述

你好朋友我需要你的帮助。我想在两个元组列表之间进行比较,如果两个元组之间有多个相同的值,我打印这个结果 exp:

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

输出:[0,1]

标签: pythonpython-3.xlisttuples

解决方案


使用列表理解:

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:对于重复项,这可能表现不佳。


推荐阅读