如果我有两组元组,有没有办法让交集只匹配元组的第一个元素?
如果需要,我可以在set / frozenset创建时指定它。
如果有帮助,我试图根据元组中的第一个值对两组元组进行JOIN
答案 0 :(得分:1)
first_set, second_set = {("A", 23), ("B", 15)}, {("X", 23), ("B", 42)}
# Group items based on the first elements, as dictionaries
d1, d2 = {}, {}
for item in first_set:
d1.setdefault(item[0], []).append(item)
for item in second_set:
d2.setdefault(item[0], []).append(item)
# Merge the dictionaries to form a list of grouped items
s = [d1.get(key, []) + d2.get(key, []) for key in d1.viewkeys() | d2]
# Filter out all the groups if the length is lesser than 1
print [item for item in s if len(item) > 1]
# [[('B', 15), ('B', 42)]]