如果我在 python 中有一个 ts 元组列表:
ts = [(702,703), (703,704), (803,805), (803,806), (901,903), (902,903)]
如何获取包含 2 个或更多此类元组之间的公共(public)元素的列表?
假设 ts 中的元组和元组中的元素都已经按数字排序。
对于这个例子,预期的输出应该是:
ts_output = [703, 803, 903]
以下是我目前的工作:
ts = [(702,703), (703,704), (803,805), (803,806), (901,903), (902,903)]
ts = set(ts)
t1 = set(w for w,x in ts for y,z in ts if w == y) # t1 should only contain 803
print("t1: ", t1)
t2 = set(y for w,x in ts for y,z in ts if x == y) # t2 should only contain 703
print("t2: ", t2)
t3 = set(x for w,x in ts for y,z in ts if x == z) # t3 should only contain 903
print("t3: ", t3)
这是相应的输出:
t1: {803, 901, 902, 702, 703}
t2: {703}
t3: {704, 805, 806, 903, 703}
从上面看,只有 t2 给出了预期的输出,但我不确定 t1 和 t3 发生了什么。
您可以使用这个替代输入来测试您的代码,它应该给出完全相同的输出:
ts = [(701,703), (702,703), (703,704), (803,805), (803,806), (901,903), (902,903), (903,904)]
请您参考如下方法:
import collections
ts = [(702,703), (703,704), (803,805), (803,806), (901,903), (902,903)]
flat_list = [item for sublist in ts for item in sublist]
duplicates = [item for item, count in collections.Counter(flat_list).items() if count > 1]
print(duplicates)
说明:
根据您的输入,您首先需要扁平化您的列表。
#1 Simple and pythonic
flat_list = [item
for sublist in ts
for item in sublist]
#2 More efficient.
import itertools
flat_list = itertools.chain.from_iterable(ts)
在方法 #1 的情况下,您的 flat_list 将是 list 对象,在方法 #2 的情况下,它将是 generator 对象。两者在迭代中的行为相同。
现在您可以计算 flat_list 中的元素了。如果它们大于 1,则它们是重复的。
for item, count in collections.Counter(flat_list).items():
if count > 1:
print(item)
或者您可以使用更多 pythonic 列表理解。
duplicates = [item
for item, count in collections.Counter(flat_list).items()
if count > 1]
