![](/img/trans.png)
[英]Python: Is there a way to count the frequency of a number in a list by only using a counting variable and appending an empty list?
[英]Simplify counting and appending to a list
好吧,必須有一個更清潔的方法來做到這一點。 我仍然是業余程序員,但我覺得他們有一些東西可以縮短這一點。 所以基本上我有這個數字數據集,並且我將1,2,3,4,5,6,7,8,9的出現計為第一個數字,然后將計數附加到列表中。 這肯定似乎很長,我必須這樣做
countList = []
for elm in pop_num:
s = str(elm)
if (s[0] == '1'):
count1 += 1
if (s[0] == '2'):
count2 += 1
if (s[0] == '3'):
count3 += 1
if (s[0] == '4'):
count4 += 1
if (s[0] == '5'):
count5 += 1
if (s[0] == '6'):
count6 += 1
if (s[0] == '7'):
count7 += 1
if (s[0] == '8'):
count8 += 1
if (s[0] == '9'):
count9 += 1
countList.append(count1)
countList.append(count2)
countList.append(count3)
countList.append(count4)
countList.append(count5)
countList.append(count6)
countList.append(count7)
countList.append(count8)
countList.append(count9)
你可以使用collections.Counter
(基本上是一個專門用於計算事物的特殊字典)和列表推導(用於編寫簡單循環的更簡潔的語法)在兩行中完成此操作。
這是我怎么做的。
import collections
counts = collections.Counter(str(x)[0] for x in pop_num)
countList = [counts[str(i)] for i in range(1,10)]
編輯:以下是如何在不使用collections
情況下獲得等效功能。
counts = {}
for x in pop_num:
k = str(x)[0]
counts.setdefault(k, 0)
counts[k] += 1
countList = [counts[str(i)] for i in range(1,10)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.