【问题标题】:Coding a function in python wihch count the number of occurances [closed]在python中编写一个计算出现次数的函数[关闭]
【发布时间】:2018-01-01 19:42:34
【问题描述】:

我是 python 的初学者,我希望编写一个具有可变数量参数的函数。此函数必须计算所有输入字符串中存在的每个字符的出现次数。 让我们将此函数重命名为 carCompt。

例如:

carCompt("Sophia","Raphael","Alexandre")

结果应该是:

{'A':5,
 'D':1,
 'E':3,
 'H':2,
 'L':1,
 'N':1,
 'O':1,
 'P':2,
 'R':2,
 'S':1,
 'X':1}

谢谢你的帮助!!

【问题讨论】:

  • 你试过什么?你被困在哪里了?不幸的是,正如所写,这是一个“为我编写代码”的问题。这不是免费的代码编写服务。请相应地编辑您的问题。
  • 尝试使用字典作为起点。

标签: python python-3.x python-2.7


【解决方案1】:

使用集合模块来使用计数器功能。如:

import collections

def carCompt(*args):
    return collections.Counter("".join(map(str.upper, args)))

这将返回

{'A':5,
 'D':1,
 'E':3,
 'H':2,
 'L':1,
 'N':1,
 'O':1,
 'P':2,
 'R':2,
 'S':1,
 'X':1}

如果您希望它区分大小写,请保留如下:

import collections

def carCompt(*args):
    return collections.Counter("".join(args))

这将返回

{'a': 4, 'e': 3, 'p': 2, 'h': 2, 'l': 2, 'S': 1, 'o': 1, 'i': 1, 'R': 1, 'A': 1, 'x': 1, 'n': 1, 'd': 1, 'r': 1}

我还建议按照PEP8 将函数名称从 carCompt 更改为 car_compt。

【讨论】:

  • @Rahul K P 是的,我们应该首先:导入集合
猜你喜欢
  • 1970-01-01
  • 2017-03-04
  • 2018-06-27
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2015-09-30
相关资源
最近更新 更多