ValueError:需要多于 0 个值来解包(python 列表)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13891813/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:52:06  来源:igfitidea点击:

ValueError: need more than 0 values to unpack (python lists)

python

提问by kunaguvarun

I'm learning python from Google code class. I'm trying out the exercises.

我正在从 Google 代码课学习 python。我正在尝试练习。

def front_x(words):
  x_list, ord_list = []
  for word in words:
    if word[0] == 'x':
      x_list.append(word)
    else:
      ord_list.append(word)
  return sorted(x_list) + sorted(ord_list)      

I believe the error is thrown because of initializing two empty lists on a single line. If if initialize them on separate lines, no more errors occur. Is this the reason?

我相信错误是由于在一行上初始化两个空列表而引发的。如果在单独的行上初始化它们,则不会发生更多错误。这是原因吗?

采纳答案by Martijn Pieters

You are trying to use tuple assignment:

您正在尝试使用元组分配:

x_list, ord_list = []

you probably meant to use multiple assignment:

你可能打算使用多重赋值:

x_list = ord_list = []

which will not do what you expect it to; use the following instead:

这不会做你期望的事情;请改用以下内容:

x_list, ord_list = [], []

or, best still:

或者,最好还是:

x_list = []
ord_list = []

When using a comma-separated list of variable names, Python expects there to be a sequence of expressions on the right-hand side that matches the number variables; the following would be legal too:

当使用逗号分隔的变量名列表时,Python 期望右侧有一个与数字变量匹配的表达式序列;以下也是合法的:

two_lists = ([], [])
x_list, ord_list = two_lists

This is called tuple unpacking. If, on the other hand, you tried to use multiple assignment with oneempty list literal (x_list = ord_list = []) then both x_listand ord_listwould be pointing to the samelist and any changes made through one variable will be visible on the other variable:

这称为元组解包。如果,另一方面,您尝试使用多任务与一个空列表文字(x_list = ord_list = []两者),然后x_listord_list将指向相同的列表,并通过一个变量作中将会在其他变量可见的任何变化:

>>> x_list = ord_list = []
>>> x_list.append(1)
>>> x_list
[1]
>>> ord_list
[1]

Better keep things crystal clear and use two separateassignments, giving each variable their own empty list.

最好让事情一目了然,并使用两个单独的赋值,为每个变量提供自己的空列表。

回答by Abhijit

Change the line

换线

x_list, ord_list = []

to

x_list, ord_list = [], []

回答by RICHA AGGARWAL

return type of function does not match with values expected in function...

函数的返回类型与函数中预期的值不匹配...

check the number of variables returned from function and variables you are expecting

检查从函数和您期望的变量返回的变量数