在python中编写一个函数来计算出现次数[关闭]

问题描述 投票:-5回答:1

我是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个回答
1
投票

使用collections模块使用Counter函数。如:

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。

© www.soinside.com 2019 - 2024. All rights reserved.