Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的多层列表迭代_Python_Loops_Iteration - Fatal编程技术网

Python中的多层列表迭代

Python中的多层列表迭代,python,loops,iteration,Python,Loops,Iteration,我试图用Python迭代多层列表,但遇到了一个错误 example = [ [ ("Set 1"), [ ('a', 'b', 'c'), ('d', 'e', 'f') ] ], [ ("Set 2"), [ ('1', '2', '3'), ('4', '5', '6') ] ] ] for section in example: print("Section: ", s

我试图用Python迭代多层列表,但遇到了一个错误

example = [
    [ ("Set 1"),
      [ ('a', 'b', 'c'),
        ('d', 'e', 'f')
      ]
    ],
    [ ("Set 2"),
      [ ('1', '2', '3'),
        ('4', '5', '6')
      ]
    ]
]

for section in example:
    print("Section: ", section)
    for section_name, section_vals in section:
        print("Name: ", section_name)
        print("Values: ", section_vals)
我得到的错误是:
ValueError:要解包的值太多(预期为2个)

我希望看到的输出是:

Section: ['Set 1', [('a', 'b', 'c'), ('d', 'e', 'f')]]
Name: 'Set 1'
Values: ('a', 'b', 'c'), ('d', 'e', 'f')
Section: ['Set 1', [('1', '2', '3'), ('4', '5', '6')]]
Name: 'Set 2'
Values: ('1', '2', '3'), ('4', '5', '6')

也许这对我来说是漫长的一天,但我似乎无法找出我的错误。

对于循环,您不需要内部
。因此,代码应该如下所示:

for section in example:
    print("Section: ", section)
    section_name, section_vals=section
    print("Name: ", section_name)
    print("Values: ", section_vals)
然后输出是:

Section:  ['Set 1', [('a', 'b', 'c'), ('d', 'e', 'f')]]
Name:  Set 1
Values:  [('a', 'b', 'c'), ('d', 'e', 'f')]
Section:  ['Set 2', [('1', '2', '3'), ('4', '5', '6')]]
Name:  Set 2
Values:  [('1', '2', '3'), ('4', '5', '6')]

对于
循环,不需要内部的
。因此,代码应该如下所示:

for section in example:
    print("Section: ", section)
    section_name, section_vals=section
    print("Name: ", section_name)
    print("Values: ", section_vals)
然后输出是:

Section:  ['Set 1', [('a', 'b', 'c'), ('d', 'e', 'f')]]
Name:  Set 1
Values:  [('a', 'b', 'c'), ('d', 'e', 'f')]
Section:  ['Set 2', [('1', '2', '3'), ('4', '5', '6')]]
Name:  Set 2
Values:  [('1', '2', '3'), ('4', '5', '6')]

其他答案是正确的。 只需补充一点,您可以直接解压缩列表:

for section_name, section_vals in example:
    print("Name: ", section_name)
    print("Values: ", section_vals)

其他答案是正确的。 只需补充一点,您可以直接解压缩列表:

for section_name, section_vals in example:
    print("Name: ", section_name)
    print("Values: ", section_vals)