[英]Multi-Layer List Iteration in Python
I am trying to iterate through multi-layered lists in Python and am encountering an error. 我试图遍历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)
The error I am getting is: ValueError: too many values to unpack (expected 2)
我得到的错误是:
ValueError: too many values to unpack (expected 2)
The output I am expecting to see is: 我期望看到的输出是:
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')
Maybe it's just been a long day for me but I can't seem to figure out my error. 也许这对我来说是漫长的一天,但我似乎无法弄清我的错误。
You don't need the inner for
loop. 您不需要内部的
for
循环。 Thus, the code should look like: 因此,代码应如下所示:
for section in example:
print("Section: ", section)
section_name, section_vals=section
print("Name: ", section_name)
print("Values: ", section_vals)
And then the output is: 然后输出是:
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')]
The other answers are correct. 其他答案是正确的。 Just to add that you can directly unpack the list:
只需添加一下,您就可以直接解压缩列表:
for section_name, section_vals in example:
print("Name: ", section_name)
print("Values: ", section_vals)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.