[英]How to make a counting function that returns the number of elements in a list
我正在尝试创建一个计算列表中元素的函数,而我正在使用Python。 该程序应接受[a, a, a, b, b, c, c, c, c]
并返回值[3, 2, 4]
但我遇到了麻烦。 我该怎么办?
如果给定['a', 'a', 'a', 'b', 'b', 'a']
您想要[3, 2, 1]
:
import itertools
result = [len(list(iterable)) for _, iterable in itertools.groupby(my_list)]
使用字典并对其作出反击。
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库中的OrderedDict方法。
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.