如何通过特定元素获得两组元组的交互?

2024-05-23 16:01:07 发布

您现在位置:Python中文网/ 问答频道 /正文

有两组s1{(1, 'string111'), (2, 'string222')}和s2{(2, 'string333'), (3, 'string444')}。我可以通过id(元组中的第一个元素)获得这两个集合的交互吗。所以我实际上想要得到的交互是{1, 2} & {2, 3},但是返回{2, 'string222'}。还是使用其他数据结构而不是元组集更好?你知道吗


Tags: id元素数据结构元组s2s1string333string222
3条回答

或者为什么不:

print({i for i in s1 if {i[0]}==set.intersection(set(map(lambda x:x[0],s1)),set(map(lambda x:x[0],s2)))})

输出:

{(2, 'string222')}

或者为什么不:

print({i for i in s1 if i[0] in map(lambda x:x[0],s2)})

输出:

{(2, 'string222')}

itemgetter

from operator import itemgetter
print({i for i in s1 if i[0] in map(itemgetter(0),s2)})

输出:

{(2, 'string222')}

s1查找id2中的每个tuples2中的所有id上设置set

s1 = {(1, 'string111'), (2, 'string222')}
s2 = {(2, 'string333'), (3, 'string444')}

id2 = {x[0] for x in s2}        # all the id in s2
filtered = list(filter(lambda x: x[0] in id2, s1))  # lookup id2 and filter
print(filtered)                 # => [(2, 'string222')]

非FP版本

id2 = {x[0] for x in s2}
ret = set()
for x in s1:
    if x[0] in id2:
        ret.add(x)
print(ret)      # => {(2, 'string222')} 

我认为将集合转换为字典更方便:

d1 = dict(s1)  # {1: 'string111', 2: 'string222'}
d2 = dict(s2)  # {2: 'string333', 3: 'string444'}

for i in d1:
    if i in d2:
        print(i, d1[i])
# 2 string222

或更简洁(使用集合理解):

{(i, d1[i]) for i in d1 if i in d2}  # {(2, 'string222')}

# equivalently {(i, d1[i]) for i in d1.keys() & d2.keys()}

相关问题 更多 >