简体   繁体   中英

Can't unpack tuples when tuple of tuples has single tuple. Why? Works with array of tuples

Why can't a single tuple in an tuple of tuples be unpacked? A single tuple in any array of tuples does work, however.

Tuple of Tuples (many tups) --- Works

mytup=(([1,2,3],['a','b','c'],99),([2,2,3],['b','b','c'],100))
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

99
100

Tuple of Tuples (single tup) --- Does not work

mytup=(([1,2,3],['a','b','c'],99))
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

3
c
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-171-1c4755f1cb92> in <module>
     13 mytup=(([1,2,3],['a','b','c'],99)) #,([2,2,3],['b','b','c'],100))
     14 for t in mytup:
---> 15     z1,z2,z3=t
     16     print(z3)

TypeError: cannot unpack non-iterable int object

Array of Tuples --- Works

mytup=[([1,2,3],['a','b','c'],99)]
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

99

只需在最后一个右括号之前放置一个逗号即可显示它是一个元组:

mytup = (([1,2,3],['a','b','c'],99),)

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