迭代元组中的元素 (Python)

Iterate over elements in tuple (Python)

我是编程新手,出于练习的原因,我尝试遍历元组中的元素,然后为每个不同的元素指定一个索引。

我在迭代元组时遇到问题,这是我的代码:

p.s:我使用enumerate来为每个元组保留一个索引。

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for x, y, z in enumerate (tup):
        print(x, y, z)

但是我得到这个错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-72-cfb75f94c0bb> in <module>
     17 myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
     18 for tup in myList:
---> 19     for x, y, z in enumerate (tup):
     20         print(x, y, z)

ValueError: not enough values to unpack (expected 3, got 2)

我给了 3 个元素来解压,但我还是遇到了那个错误。解包 3 个元素的元组的正确方法是什么?

I gave 3 elements to unpack and I got anyway that error. Which is the correct way to unpack tuples of 3 elements?

问题是 for 循环基本上已经为您解包了元组。例如:

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for x in tup:
        print(x)

要正确使用 enumerate(),您需要解压从它返回的两个元素:

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for i, x in enumerate(tup):
        print(i, x)

如果相反,您想要父列表中每个元组的索引,则需要在外循环中enumarate(myList)

for i, (x, y, z) in enumerate(myList):
    print(i, x, y, z)