簡體   English   中英

如何使計數函數返回列表中的元素數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM