문제

I run this code:

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)

And get this error:

word,score,std = string.split()
ValueError: need more than 1 value to unpack
도움이 되었습니까?

해결책

It's because string.lower().split() is returning a list with only one item. You cannot assign this to word,score,std unless this list has exactly 3 members; i.e. string contains exactly 2 spaces.


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

다른 팁

This fails, since the string contains only one word:

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

This works, because the number of words is the same as the number of variables:

string = "This one works"
word, score, std = string.split()
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)

I think this is what you are looking for, so correct me if I am wrong, but this basically checks if there are any spaces in which split() can split on, and acts accordingly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top