![](/img/trans.png)
[英]Count words in a list and add them to a dictionary, along with number of occurrences Python
[英]Count the number of words in dictionary from a list
給定一個列表:
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
和一本字典
dict = {'orange': 4, 'apple':2, 'pears': 1}
如果列表中的字符串已存在於dict中,則更新值;否則,添加新的鍵及其計數。
結果:
dict = {'orange' = 5, 'apple':3, 'pears':3, 'banana':1}
我試過了:
count = 0
for string on lst:
if string in dict.keys():
for num in dict:
count = count + num
num = count
我不知道如何繼續
您可以使用collections.Counter
from collections import Counter
>>> lst = ['apple', 'orange', 'pears', 'pears', 'banana']
>>> d = {'orange': 4, 'apple':2, 'pears': 1}
>>> count = Counter(d)
>>> count
Counter({'orange': 4, 'apple': 2, 'pears': 1})
>>> count += Counter(lst)
>>> count
Counter({'orange': 5, 'pears': 3, 'apple': 3, 'banana': 1})
盡管存在其他有效的方法,但可以使用簡單的列表循環和dict.get
方法輕松完成此操作。
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
dict = {'orange': 4, 'apple':2, 'pears': 1}
for st in lst:
dict[st] = dict.get(st,0)+1
dict
{'orange': 5, 'apple': 3, 'pears': 3, 'banana': 1}
您的答案幾乎是正確的:
for string in lst:
if string in dict.keys():
dict[string] += 1
else:
dict[string] = 1
這是假設您尚未看到的字符串以值1開頭,對於您的輸出來說似乎是這種情況。
您還可以刪除.keys(),因為python會自動在鍵中檢查您要循環播放的值,因此:
for string in lst:
if string in dict:
dict[string] += 1
else:
dict[string] = 1
前延伸,還有在第2行錯字,這應該是在列表中的字符串。
這是我建議的解決方案。 當您遍歷列表時,請檢查每個條目以查看它是否是字典中的鍵(如已完成)。 如果是,那么dict [string]將是與該鍵配對的數字值,您可以將其添加一個。 如果不是,則可以將字符串添加為值為1的新鍵。
# original data
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
dict = {'orange': 4, 'apple':2, 'pears': 1}
# iterate through lst and add 1 to each corresponding key value
for string in lst:
if string in dict.keys():
# increment count for a found key
# which can be accessed in dict[string] - no need for num
count = int(dict[string])
dict[string] = count + 1
else:
# add new key and a count of 1 to dict
dict[string] = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.