开发者

Counting with python dictionaries and adding functionality

 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: ????

Hey, I'm trying to do two things here: 1) count how many occurrences of a certain word (in this case, certain types of fruit), appear in a document- which I am attempting to simulate here with a simple input function. I know it's not perfect, but I can't figure out how to make each occurrence increase the value for the appropriate key incrementally. For instance, if I call this function twice and type "lemons", the count should be 2, but it remains 1. In other words, my function is a lemon, but I don't know why.

The last thing I am having trouble with is the else function. 2 ) My program will be looking in pre-defined sections of a document, and I would like my else function to create a key: value pair in the dictionary if the existing key does not 开发者_如何学运维exist. For instance, if my program encounters the word 'banana', I would like to add the k:v pair { 'banana': [] } to the current dictionary so I can start counting those occurrences. But it seems like this would require me to not only add the k:v pair to the dictionary (which I don't rightly know how to do), but to add a function and variable to count the occurrences like the other k:v pairs.

Does this entire set up make sense for what I'm trying to do? Please help.


You seem to have multiple variables called fruit, that's a bad idea. And if you're just counting, you should start with 0, not []. You can write your code way easier as:

import collections
result = collections.defaultdict(int)
def count():
    fruit = input("What fruit are you getting at the store? ")
    result[fruit] += 1

In Python 3.1+, you should use collections.Counter instead of collections.defaultdict(int). If you don't want to use the collections module at all, you could also write out the defaultdict functionality:

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


You might do it by this way:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜