簡體   English   中英

將字典中的鍵與字符串列表進行比較並對值進行求和

[英]Comparing keys from dictionaries to a list of strings and summing the values

所以我做了一個字典,鍵是單詞,值是與每個單詞相關的數值。 我也有一個單詞列表。 我想取列表中的單詞,看看它們中是否有任何字典。 如果列表中的單詞在字典中,我需要能夠將與每個單詞相關聯的值相加。

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
list = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

使用列表理解:

dictionary = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
lst = ["I", "am", "so", "happy", "this", "is", "the", "greatest", "day", "ever", "I", "am", "so", "excited", "!"]

print sum([dictionary[i] for i in lst if i in dictionary])

您可以使用getdict有一個默認值返回如果該鍵不存在。

此外,即使在一個示例中,字典和列表也不是好的變量名稱:

>>> weights = {"happy": 5, "greatest": 10, "best": 5, "excited": 10}
>>> sentence = 'I am so happy this is the greatest day ever I am so excited !'

>>> sum(weights.get(word, 0) for word in sentence.split())
20

不要將列表用作變量名(它是關鍵字)

這段代碼可以滿足您的需求:

sum_value = 0
for item in list1:
    if item in dictionary:
        sum_value += dictionary[item]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM