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()}
或者为什么不:
输出:
或者为什么不:
输出:
或
itemgetter
:输出:
为
s1
查找id2
中的每个tuple
在s2
中的所有id上设置set
非FP版本
我认为将集合转换为字典更方便:
或更简洁(使用集合理解):
相关问题 更多 >
编程相关推荐