如何添加两组

GTh*_*izh 29 python set python-3.x

a = {'a','b','c'} 
b = {'d','e','f'}
Run Code Online (Sandbox Code Playgroud)

我想在上面添加两个设定值.

需要输出,如,

c = {'a','b','c','d','e','f'}
Run Code Online (Sandbox Code Playgroud)

The*_*Cat 45

这不是一个c = a|b,它是一个a|b.你需要做的就是把它们结合起来union.

集是唯一值的无序序列. c = a|ba|b两个集合中的一个集合(一个新集合,其中包含在任一集合中找到的所有值).这是一类称为"set operation"的操作,它为set提供了方便的工具.

  • 您也可以执行 `c |= a | b` 如果 C 已经是一个集合并且您想要就地更新 (5认同)

Har*_*ara 21

你可以使用update()将set(b)组合成set(a)试试这个.

a = {'a', 'b', 'c'}
b = {'d', 'e', 'f'}
a.update(b)
print a
Run Code Online (Sandbox Code Playgroud)

第二个解决方案是:

c = a.copy()
c.update(b)
print c
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在 c 中使用 a 和 b 的 union() 结果。注意:sorted() 用于打印排序后的输出

    a = {'a','b','c'} 
    b = {'d','e','f'}
    c=a.union(b)
    print(sorted(c)) #this will print a sorted list
Run Code Online (Sandbox Code Playgroud)

或者简单地打印 a and 的 unsorted union

    print(c)  #this will print set c
Run Code Online (Sandbox Code Playgroud)