如何制作一个返回lis中元素个数的计数函数

2024-04-20 05:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数来统计列表中的元素,我正在使用Python来实现这一点。程序应该接受一个类似[a, a, a, b, b, c, c, c, c]的列表并返回一个值[3, 2, 4],但是我遇到了问题。我该怎么办?你知道吗


Tags: 函数程序元素列表
2条回答

用听写器做一个计数器。你知道吗

a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = {}
for i in inp:
    if i in dic:
        dic[i]+=1
    else:
        dic[i] = 1
print(dic)  #Dict with input values and count of them
print(dic.values())  #Count of values in the dict

请记住,这会更改输入列表的顺序。 要保持订单完整,请使用Collections库中的orderedict方法。你知道吗

from collections import OrderedDict
a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = OrderedDict()
for i in inp:
    if i in dic:
        dic[i]+=1
    else:
        dic[i] = 1
print(dic)
print(dic.values())

如果给定['a', 'a', 'a', 'b', 'b', 'a']时需要[3, 2, 1]

import itertools
result = [len(list(iterable)) for _, iterable in itertools.groupby(my_list)]

相关问题 更多 >