我有一個字符串,詞典形式列表理解:與平均值
('The puppy likes flowers',
{'laughter': (8.5, 0.9313),
'flowers': (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),
'likes':(5.9, 0.032),
'like':(6.5, 0.021)
}
)
每個括號是對應於(得分,標準偏差)的元組。我正在取每個元組中第一個整數的平均值。我已經試過這樣:
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 ('The puppy likes 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)})
我應該得到的只是'the'
平均,'puppy',
'likes'
和'flowers'
:4.98 + 7.88 + 5.9 + 7.58/4
但這運行功能還包括'like'
和'flow'
:4.98 + 7.88 + 5.9 + + 7.58 + 6.5 + 2.3/6
。
有幾點需要澄清你的問題[1]你有一個元組,[2]'string'是變量的錯誤名稱(它是內置的名稱)和[3]'如果len(string)== 0:'可以簡化爲'如果不是len(string):' –
你甚至不需要檢查長度。 Python會爲你做,只需使用如果不是字符串:return None –
類似的帖子:http:// stackoverflow。com/questions/13006271/using-list-comprehension –