首页 > 解决方案 > 如何在python中找到具有重复元素的元组?

问题描述

我有一个格式的列表

unique_edges=[('SLT2', 'SDP1'),('GCD7', 'ATG34'),('MTH1', 'MTH1'),('ADY2', 'ADY2')]

我需要使用列表理解(一行代码)将具有相同元素的元组两次(如('MTH1','MTH1'))移动到新列表。

我想我需要使用类似的东西

homo_dimers = list(map(tuple,unique_edges))

但我不知道如何使用这些函数在一个元组中搜索重复的元素。

标签: pythonlisttuples

解决方案


List comprehension to find tuples with same element:

homo_dimers = [(a, b) for a, b in unique_edges if a == b]
print(homo_dimers)

Prints:

[('MTH1', 'MTH1'), ('ADY2', 'ADY2')]

Or if your tuples contain more than 2 elements:

homo_dimers = [t for t in unique_edges if len(set(t)) == 1]

推荐阅读