简体   繁体   English

用元组的元组解包错误?

[英]Unpack error with tuple of tuples?

I want to iterate over the elements ((a,b),(x,y)) so I tried: 我想遍历元素((a,b),(x,y)),所以我尝试了:

def method(tuple):
    ((a,b),(x,y))= tuple
    for element in tuple:
    .....

But then I read another stackoverflow page which suggested something like this: 但是随后我阅读了另一个stackoverflow页面,其中提出了类似以下内容:

def method(tuple):
    ((a,b),(x,y))= tuple
    for element in tuple[0:4]:
    .....

Both resulted in the error: ValueError: need more than 1 value to unpack. 两者均导致错误:ValueError:需要多个值才能解压。

Is this action not allowed in python, or do I just have a syntax problem? 是python不允许执行此操作,还是我有语法问题? I have checked the python docs as well. 我也检查了python文档。

Thanks for any advice. 感谢您的任何建议。

Edit 编辑

map = ((1,0),(3,2))
    def count(map):
        ((a,b),(x,y))= tuple
        inc=0
        for element in tuple:
            inc+=1

If you have a tuple of tuples, of the form ((a, b), (x, y)) , you can iterate over its elements: 如果您具有((a, b), (x, y))形式的元组,则可以遍历其元素:

def method(tuples):
    for tup in tuples:
        for e in tup:
            print e

If you want to have 4 variables, you can use them separately: 如果要有4个变量,可以分别使用它们:

def method(tuples):
    (a, b), (x, y) = tuples
    print a, b, x, y

Note: Don't use Python built-in names as name of variables. 注意:请勿将Python内置名称用作变量名称。 In other words, don't use tuple as a name of a variable because it's a type in Python. 换句话说,不要将tuple用作变量的名称,因为它是Python中的类型 Use something else, like tuples , my_tuple , ... 使用其他内容,例如tuplesmy_tuple ,...

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

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