【问题标题】:Counting with python dictionaries and adding functionality使用 python 字典计数并添加功能
【发布时间】:2011-06-02 12:31:42
【问题描述】:
 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 函数在字典中创建一个 key: value 对,如果现有的 key 不存在。例如,如果我的程序遇到单词 'banana',我想将 k:v 对 { 'banana': [] } 添加到当前字典中,这样我就可以开始计算这些出现了。但这似乎需要我不仅将 k:v 对添加到字典中(我不知道该怎么做),而且还需要添加一个函数和变量来像其他 k:v 一样计算出现次数对。

整个设置对我想要做的事情有意义吗?请帮忙。

【问题讨论】:

  • 你正在调用你的字典,“fruit”和你的输入变量“fruit”......这不会很好用。

标签: python dictionary counter


【解决方案1】:

您似乎有多个名为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

【讨论】:

  • @katrielalex 更新了,反正没有人使用 Python 3.0。
  • 我的意思是 Counter 在 2.7 中...应该说清楚!我的错。
  • @katrielalex 不,我理解你很好。 Counterrange(2.7, 3)range(3.1, infinity) 中(即不在3.0 中)。
【解决方案2】:

你可以这样做:

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

【讨论】:

  • has—key 已被弃用,使用 in 代替。
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
相关资源
最近更新 更多