简体   繁体   中英

Make tuple of sets in Python

I want to put two sets in a tuple in Python.

set1 = set(1, 2, 3, 4)
set2 = set(5, 6, 7)

What I've tried:

result = tuple(set1, set2)
# got error "TypeError: tuple expected at most 1 argument, got 2"

Desired output:

({1, 2, 3, 4}, {5, 6, 7})

A tuple literal is just values separated by commas.

set1 = {1,2,3,4}
set2 = {5,6,7}
result = set1, set2

or if you find it clearer

result = (set1, set2)

The tuple(x) form is useful when you have an iterable sequence x that you want to transform to a tuple.

set and tuple constructors take only one argument: an iterable. Wrap your arguments in a list and it should work.

set1 = set([1, 2, 3, 4])
set2 = set([5, 6, 7])
result = tuple([set1, set2])  # or (set1, set2)
print(result)  # ({1, 2, 3, 4}, {5, 6, 7})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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