2012-10-22 43 views
2

我有一個字符串,詞典形式:使用列表理解

('(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

+0

你必須反過來循環:不是在字典中用單詞表示字符串中的單詞,而是用單詞string.split()中的單詞表示。 – georg

+0

這樣做會給我一個ZeroDivisionError @ thg435 –

+0

抱歉,這裏沒有在線調試服務。 – georg

回答

2

@Ignaco是正確的,爲什麼你包括「流」和「笑」 ......

你可以編寫代碼爲雖然以下幾點:

data = ('(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)}) 

# Unpack for naming 
keys, vals = data 
# Assume() and first and last 
look_for = keys[1:-1].lower().split() 
# Get relevant numbers 
nums = [vals[k][0] for k in look_for] 
# Print average 
print sum(nums)/len(nums) 

所以你推廣的功能,只是平均相關按鍵的第一個元素:

def somefunc(keys, dct): 
    vals = [dct[k][0] for k in keys] 
    return sum(vals)/float(len(vals)) 

而且你必須預先處理一些字符串不知何故,所以它是有效的鍵序列: '(笑花)'

some_string = '(laughter flower)' 
keys = some_string[1:-1].lower().split() 
print somefunc(keys, some_dict) 
+0

如果我的字符串,字典可以是任何東西,該怎麼辦?我不想將「數據」標識爲特定的內容。 @JonClements –

+0

@BillyMann我不明白你如果它不是一個字符串,也不是一本字典,那麼你必須有一個不同的方法... –

+0

這是一個字符串和字典,但我的觀點函數是調用任何給定字典中的字符串。 @JonClements –

1

是這樣的:

In [65]: lis=('(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)}) 

In [68]: strs=lis[0].strip('()').split() # returns ['Laughter', 'flower'] 

In [69]: lis1=[lis[1][x][0] for x in lis[1] if x in map(str.lower,strs)] 

In [70]: sum(lis1)/float(len(lis1)) 
Out[70]: 8.1899999999999995 
0
def score(string,d): 
    if string=="": 
     return 0 
    string=string.lower().split() 
    included=[d[word][0] for word in d if word in string] 
    return(sum(included)/len(included)) 

您的字符串=

它的字符串不是兩個不同的單詞,所以當你申請 [d [單詞] [0]單詞在d 如果單詞在字符串中]它沒有得到這個詞。 因此,如果您不希望在字符串周圍使用()括號,它會很容易。 改爲使用'笑花'。 但仍然是它的一個字符串不是兩個字所以你必須拆分它string.split()它會 創建一個兩個單詞的列表,然後你的函數將工作。