Python中的多层列表迭代

时间:2017-07-20 19:11:36

标签: 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: ", section)
    for section_name, section_vals in section:
        print("Name: ", section_name)
        print("Values: ", section_vals)

我得到的错误是:ValueError: too many values to unpack (expected 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')

也许这对我来说只是漫长的一天,但我似乎无法弄清楚我的错误。

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

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

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