2012-10-20 2 views
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

string.lower().split() 단 하나의 항목 목록을 반환 때문입니다. 이 목록에 정확히 3 명의 구성원이 없으면 이것을 word,score,std에 할당 할 수 없습니다. 즉 에는 정확히 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 
0

이는 실패

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

단어의 수가 변수의 수와 동일하기 때문에이 작품 :

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

나는 이것이 당신이 찾고있는 것이라고 생각합니다. o 틀렸다면 나를 바로 잡으십시오. 그러나 이것은 기본적으로 split()이 나눌 수있는 공백이 있는지 검사하여 그에 따라 작동합니다.

관련 문제