Python 列表列表和“解包的值太多”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3386107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List of lists and "Too many values to unpack"
提问by Bitrex
I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:
我正在尝试在列表列表上使用以下代码来创建一个新的列表列表,其新元素是旧列表中列表中元素的某种组合......如果这有意义的话!这是代码:
for index, item in outputList1:
outputList2 = outputList2.append(item[6:].extend(outputList1[index+1][6:]))
However, I get a "Too many values to unpack" error. I seem to even get the error with the following code:
但是,我收到“要解压缩的值太多”错误。我似乎什至收到以下代码的错误:
for index, item in outputList1:
pass
What could I be doing wrong?
我可能做错了什么?
采纳答案by Carson Myers
the forstatement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.
该for语句迭代一个可迭代对象——在列表的情况下,它一个一个地迭代内容,因此在每次迭代中,一个值可用。
When using for index, item in list:you are trying to unpack one value into two variables. This would work with for key, value in dict.items():which iterates over the dicts keys/values in arbitrary order. Since you seem to want a numerical index, there exists a function enumerate()which gets the value of an iterable, as well as an index for it:
使用时,for index, item in list:您试图将一个值解包为两个变量。这将适用for key, value in dict.items():于以任意顺序迭代 dicts 键/值。由于您似乎想要一个数字索引,因此存在一个enumerate()获取可迭代值的函数以及它的索引:
for index, item in enumerate(outputList1):
pass
edit: since the title of your question mentions 'list of lists', I should point out that, when iterating over a list, unpacking into more than one variable will work ifeach list item is itself an iterable. For example:
编辑:由于您的问题的标题提到了“列表列表”,我应该指出,在迭代列表时,如果每个列表项本身都是可迭代的,那么解压缩到多个变量将起作用。例如:
list = [ ['a', 'b'], ['c', 'd'] ]
for item1, item2 in list:
print item1, item2
This will output:
这将输出:
a b c d
as expected. This works in a similar way that dicts do, only you can have two, three, or however many items in the contained lists.
正如预期的那样。这与 dicts 的工作方式类似,只有您可以在包含的列表中拥有两个、三个或任意多个项目。
回答by Andrew
You've forgotten to use enumerate, you mean to do this:
您忘记使用枚举,您的意思是这样做:
for index,item in enumerate(outputList1) :
pass

