简体   繁体   English

迭代元组中的元素(Python)

[英]Iterate over elements in tuple (Python)

I am new in programming, and for practice reasons, I trying to iterate over elements in a tuple and after give to each different element an index.我是编程新手,出于实践原因,我尝试迭代元组中的元素,然后为每个不同的元素提供一个索引。

I have a problem iterating over tuples, here is my code:我在迭代元组时遇到问题,这是我的代码:

ps: I use enumerate in order to keep an index for each tuple. ps:我使用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)

But i get the this error:但我得到这个错误:

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

I gave 3 elements to unpack and I got anyway that error.我给了 3 个要解包的元素,但无论如何我都得到了那个错误。 Which is the correct way to unpack tuples of 3 elements?哪个是解包 3 个元素的元组的正确方法?

I gave 3 elements to unpack and I got anyway that error.我给了 3 个要解包的元素,但无论如何我都得到了那个错误。 Which is the correct way to unpack tuples of 3 elements?哪个是解包 3 个元素的元组的正确方法?

The problem is that the for loop is basically unpacking the tuple for you already.问题是for循环基本上已经为您解包了元组。 For example:例如:

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)

To use enumerate() correctly, you need to unpack the two elements that are returned from it:要正确使用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)

If instead, you want the index of each tuple in the parent list, you need to enumarate(myList) in the outer loop:相反,如果您想要父列表中每个元组的索引,则需要在外循环中enumarate(myList)

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

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

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