【问题标题】:More than one value to unpack多个值要解压
【发布时间】:2012-10-11 00:43:38
【问题描述】:
我运行这段代码:
def score(string, dic):
for string in dic:
word,score,std = string.lower().split()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
并得到这个错误:
word,score,std = string.split()
ValueError: need more than 1 value to unpack
【问题讨论】:
标签:
python
string
dictionary
arguments
iterable-unpacking
【解决方案1】:
这是因为 string.lower().split() 返回一个只有一个项目的列表。除非此列表正好有 3 个成员,否则您不能将其分配给 word,score,std;即string 正好包含 2 个空格。
a, b, c = "a b c".split() # works, 3-item list
a, b, c = "a b".split() # doesn't work, 2-item list
a, b, c = "a b c d".split() # doesn't work, 4-item list
【解决方案2】:
def score(string, dic):
if " " in dic:
for string in dic:
word,score,std = string.lower().split()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
else:
word=string.lower()
dic[word]=float(score),float(std)
v = sum(dic[word] for word in string)
return float(v)/len(string)
我认为这就是你要找的东西,如果我错了,请纠正我,但这主要是检查是否有任何空格可以让split() 分割,并采取相应的行动。
【解决方案3】:
这失败了,因为字符串只包含一个单词:
string = "Fail"
word, score, std = string.split()
这行得通,因为单词的数量与变量的数量相同:
string = "This one works"
word, score, std = string.split()