我有一個字符串,詞典形式:使用列表理解
('(Laughter flower)',
{'laughter': (8.5, 0.9313),
'flower': (7.88, 1.1718),
'the': (4.98, 0.9145),
'puppy': (7.58, 1.4581),
'died': (1.56, 1.198),
'laugh': (9.5, 0.1),
'flow': (2.3, 0.51)
}
)
每個括號是對應於(得分,標準偏差)的元組。我正在取每個元組中第一個整數的平均值。我已經試過這樣:
def score(string, d):
if len(string) == 0:
return 0
string = string.lower()
included = [d[word][0]for word in d if word in string]
return sum(included)/len(included)
當我運行:
print score ('(Laughter flower)', {'laughter': (8.5, 0.9313), 'flower':
(7.88, 1.1718), 'the':(4.98, 0.9145), 'puppy':(7.58, 1.4581),
'died':(1.56, 1.198),'laugh': (9.5, 0.1),'flow': (2.3, 0.51)})
我應該得到的只是'laughter'
和'flower'
平均:8.5 + 7.88/2
但這運行功能還包括'laugh'
和'flow'
:8.5 + 7.88 + 9.5 + 2.3 /4
。
你必須反過來循環:不是在字典中用單詞表示字符串中的單詞,而是用單詞string.split()中的單詞表示。 – georg
這樣做會給我一個ZeroDivisionError @ thg435 –
抱歉,這裏沒有在線調試服務。 – georg