简体   繁体   English

使用 python 字典计数并添加功能

[英]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.嘿,我在这里尝试做两件事:1)计算某个单词(在这种情况下是某些类型的水果)出现在文档中的次数——我试图在这里用一个简单的输入 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.例如,如果我调用这个 function 两次并输入“柠檬”,计数应该是 2,但它仍然是 1。换句话说,我的 function 是柠檬,但我不知道为什么。

The last thing I am having trouble with is the else function.我遇到的最后一件事是 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 . 2)我的程序将在文档的预定义部分中查找,如果现有键不存在,我希望我的 else function 在字典中创建一个键:值对 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.例如,如果我的程序遇到单词 'banana',我想将 k:v 对 { 'banana': [] } 添加到当前字典中,这样我就可以开始计算这些出现了。 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.但这似乎需要我不仅将 k:v 对添加到字典中(我不知道该怎么做),而且还需要添加 function 和变量来像其他 k:v 一样计算出现次数对。

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.您似乎有多个名为fruit的变量,这是个坏主意。 And if you're just counting, you should start with 0 , not [] .如果你只是在数,你应该从0开始,而不是[] 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) .在 Python 3.1+ 中,您应该使用collections.Counter而不是collections.defaultdict(int) If you don't want to use the collections module at all, you could also write out the defaultdict functionality:如果您根本不想使用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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM