使用Python字典计数并添加功能
a = 0
b = 0
c = 0
d = 0
fruit = {
'lemons': [],
'apples': [],
'cherries': [],
'oranges': [],
}
def count():
fruit = input("What fruit are you getting at the store? ")
if fruit == 'lemons':
fruit['lemons'] = a + 1
elif fruit == 'apples':
fruit['apples'] = b + 1
elif fruit == 'cherries':
fruit['cherries'] = c + 1
elif fruit == 'oranges':
fruit['oranges'] = d + 1
else: ????
嘿,我在这里想做两件事:1)计算某个单词(在这个例子中是某些水果的名称)在文档中出现的次数——我试图用一个简单的输入函数来模拟这个过程。我知道这不是完美的,但我搞不清楚怎么让每次出现都让对应的计数值增加。比如说,如果我调用这个函数两次并输入“柠檬”,那么计数应该是2,但它却还是1。换句话说,我的函数就像个柠檬一样,但我不知道为什么。
我遇到的最后一个问题是else函数。2)我的程序会在文档的预定义部分查找,我希望我的else函数在字典中创建一个键值对,如果这个键不存在的话。举个例子,如果我的程序遇到“香蕉”这个词,我想在当前字典中添加一个键值对 { '香蕉': [] },这样我就可以开始计算这些出现次数了。但看起来这不仅需要我把这个键值对添加到字典中(我其实不太知道怎么做),还需要添加一个函数和变量来像其他的键值对一样计算出现次数。
我这样设置的整个过程对我想做的事情有意义吗?请帮帮我。
2 个回答
0
你可以这样做:
fruits = {
'lemons': 0,
'apples': 0,
'cherries': 0,
'oranges': 0,
}
fruit = input("What fruit are you getting at the store? ")
if fruits.has_key(fruit):
fruits[fruit] += 1
4
你似乎有多个叫做 fruit
的变量,这样不好。如果你只是想计数,应该从 0
开始,而不是从 []
开始。你可以把代码写得更简单一些:
import collections
result = collections.defaultdict(int)
def count():
fruit = input("What fruit are you getting at the store? ")
result[fruit] += 1
在 Python 3.1 及以上版本中,建议使用 collections.Counter
,而不是 collections.defaultdict(int)
。如果你不想使用 collections
这个模块,你也可以自己写出 defaultdict
的功能:
result = {}
def count():
fruit = input("What fruit are you getting at the store? ")
if fruit not in result:
result[fruit] = 0 # Create a new entry in the dictionary. 0 == int()
result[fruit] += 1