简体   繁体   English

元组的元组只有一个元组时,无法解包元组。 为什么? 与元组数组一起使用

[英]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 元组元组(单个tup) ---不起作用

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),)

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

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