Python中的多层列表迭代
我试图用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
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)