How do I add two sets?

后端 未结 3 826
南旧
南旧 2020-12-08 18:14
a = {\'a\', \'b\', \'c\'} 
b = {\'d\', \'e\', \'f\'}

I want to add above two set values. I need output like

c = {\'a\', \'b\', \'c\',         


        
相关标签:
3条回答
  • 2020-12-08 18:43

    You can use the result of union() of a and b in c. Note: sorted() is used to print sorted output

        a = {'a','b','c'} 
        b = {'d','e','f'}
        c=a.union(b)
        print(sorted(c))
    

    Or simply print sorted union of a and b

        a = {'a','b','c'} 
        b = {'d','e','f'}
        print(sorted(a.union(b)))
    
    0 讨论(0)
  • 2020-12-08 18:58

    All you have to do to combine them is

    c = a | b
    

    Sets are unordered sequences of unique values. a | b or a.union(b) is the union of the two sets (a new set with all values found in either set). This is a class of operation called a "set operation", which Python sets provide convenient tools for.

    0 讨论(0)
  • 2020-12-08 18:59

    You can use .update() to combine set b into set a. Try this:

    a = {'a', 'b', 'c'}
    b = {'d', 'e', 'f'}
    a.update(b)
    print(a)
    

    To create a new set, c you first need to .copy() the first set:

    c = a.copy()
    c.update(b)
    print(c)
    
    0 讨论(0)
提交回复
热议问题