3

我运行这段代码:

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
4

3 回答 3

4

这是因为string.lower().split()返回一个只有一个项目的列表。word,score,std除非此列表恰好有 3 个成员,否则您不能将其分配给;即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
于 2012-10-20T16:52:34.097 回答
0

这失败了,因为字符串只包含一个单词:

string = "Fail"
word, score, std = string.split()

这是可行的,因为单词的数量与变量的数量相同:

string = "This one works"
word, score, std = string.split()
于 2012-10-20T16:53:29.690 回答
0
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()可以分割,并采取相应的行动。

于 2012-10-20T16:57:16.663 回答