简体   繁体   中英

How to make a counting function that returns the number of elements in a list

I am trying to make a function that counts elements in a list and I am using Python for that. The program should accept a list like [a, a, a, b, b, c, c, c, c] and returns a value [3, 2, 4] but I am having trouble. What should I do?

If when given ['a', 'a', 'a', 'b', 'b', 'a'] you want [3, 2, 1] :

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

Use a dict and make a counter out of it.

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

Remember that this change the order of input list. To keep the order intact, use OrderedDict method from Collections library.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM