简体   繁体   English

Python:元组集合的联合

[英]Python: union of set of tuples

Let's say we have two sets: 假设我们有两套:

t = {('b', 3), ('a', 2)}
r = {('b', 4), ('c', 6)}

I want a union on 1st element to result in 我希望第一个元素上的联合导致

u = {('b', 3), ('a', 2), ('c', 6)}

if duplicate symbol is present in both place (example 'b' in the above) then the element of the first list should be retained. 如果两个地方都存在重复的符号(例如上面的例子'b'),那么应该保留第一个列表的元素。 Thanks. 谢谢。

Just do: 做就是了:

t = {('b', 3), ('a', 2)}
r = {('b', 4), ('c', 6)}
d = dict(r)
d.update(t)
u = set(d.items())
print(u)

Output: 输出:

{('c', 6), ('a', 2), ('b', 3)}

A little bit shorter version: 有点短版本:

s = dict((*r, *t))
set(s.items())

Output: 输出:

{('a', 2), ('b', 3), ('c', 6)}
for el in r:
    if not el[0] in [x[0] for x in t]:
        t.add(el)

t 

{('a', 2), ('b', 3), ('c', 6)}

You can't do that with set intersecion. 你不能用set intersecion做到这一点。 Two objects are either equal or they are not. 两个对象要么相等,要么不对。 Since your objects are tuples, (b, 3) and (b, 4) are not equal, and you don't get to change that. 由于你的对象是元组, (b, 3)(b, 4)不相等,你不能改变它。

The obvious way would be to create your own class and redefine equality, something like 显而易见的方法是创建自己的类并重新定义相等,例如

class MyTuple:
    def __init__(self, values):
         self.values = values

    def __eq__(self, other):
        return self.values[0] == other[0]

and create sets of such objects. 并创建这样的对象集。

Here is my one-line style solution based on comprehensions: 这是我基于理解的单行式解决方案:

t = {('b', 3), ('a', 2)}
r = {('b', 4), ('c', 6)}

result = {*t, *{i for i in r if i[0] not in {j[0] for j in t}}}

print(result)  # {('b', 3), ('a', 2), ('c', 6)}

Using conversion to dictionary to eliminate the duplicates, you can also do that, which is a quite smart solution IMHO: 使用转换到字典来消除重复,你也可以这样做,这是一个非常聪明的解决方案恕我直言:

t = {('b', 3), ('a', 2)}
r = {('b', 4), ('c', 6)}

result = {(k,v) for k,v in dict((*r,*t)).items()}

print(result)  # {('b', 3), ('a', 2), ('c', 6)}

An alternative using chain : 使用的替代方案:

from itertools import chain

t = {('b', 3), ('a', 2)}
r = {('b', 4), ('c', 6)}

result = set({k: v for k, v in chain(r, t)}.items())

Output 产量

{('b', 3), ('a', 2), ('c', 6)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM