[英]How do I count how many times a specific value has been printed from a list?
我制作了一個簡單的硬幣翻轉程序,正如其名,它翻轉硬幣並打印出價值。
我的目標是打印大量的硬幣翻轉並記錄它落在正面的次數和落在背面的次數。 但顯然我不能,因為我不知道如何計算它落在特定值上的次數。
import random
heads_or_tail = ['heads', 'tail']
def flip_coin():
flip_coin = random.choice(heads_or_tail)
print(flip_coin)
for x in range(100):
flip_coin()
collections
模塊有一個很棒的功能叫做Counter
:
import collections
import random
heads_or_tail = ['heads', 'tail']
def flip_coin():
flip_coin = random.choice(heads_or_tail)
return flip_coin
cnt = collections.Counter()
for x in range(100):
cnt[flip_coin()] += 1
輸出:
>>> cnt
Counter({'tail': 50, 'heads': 50})
或者,您可以只使用普通的dict
但這需要更多的樣板代碼:
# Alternatively, you could just use a `dict`
dict_cnt = {}
for x in range(100):
fc = flip_coin()
if fc in dict_cnt:
dict_cnt[fc] += 1
else:
dict_cnt[fc] = 1
請記住,最 Python 化的做法是使用其他人已經完善的庫——尤其是來自 Python 標准庫的庫。 因此,在計數時,我建議您使用collections.Counter
。
此外, Counter
還有更多很酷的功能,您可以在文檔中查看。
正如其他人所提到的,您可以使用傳遞給Counter
構造函數的生成器,因為它是一個可迭代的 - 這將顯着縮短您的代碼:
import collections
import random
flip_gen = (random.choice(['heads', 'tails']) for _ in range(100))
cnt = collections.Counter(flip_gen)
>>> cnt
Counter({'heads': 51, 'tail': 49})
跟蹤每個結果的計數的一種簡單方法是將它們放在一個字典中,其中每個條目對應一個特定的結果。 collections.defaultdict
對此很好,因為它負責為您初始化默認值:
from collections import defaultdict
import random
results = defaultdict(int)
for _ in range(100):
results[random.choice(['heads', 'tails'])] += 1
for result, count in results.items():
print(f"{result}: {count}")
打印如下內容:
heads: 58
tails: 42
試試這個,這是迄今為止對初學者友好的解決方案:
import random
head = []
tail = []
def flip_coin():
for _ in range(100):
flip_coin = random.choice(['heads', 'tail'])
if flip_coin == 'heads':
head.append(flip_coin)
else:
tail.append(flip_coin)
return f'heads: {len(head)}, tails: {len(tail)}'
print(flip_coin())
我喜歡@Samwise 的解決方案,如果迭代次數真的很高,我會使用生成器(范圍正在懶惰地評估)。
import random
from collections import defaultdict
heads_or_tail = ['heads', 'tail']
d = defaultdict(int)
def flip_coin(iterations):
for i in range(iterations):
result_iteration = random.choice(heads_or_tail)
d[result_iteration] += 1
yield result_iteration
然后,您可以按需調用next () 方法獲取值,如下所示:
a = flip_coin(100)
next(a)
next(a)
next(a)
next(a)
輸出 :
defaultdict(int, {'heads': 1, 'tail': 3})
如果您沒有理由忘記每個單獨巡回賽的結果,我會推薦相反的方式。 原因可能是內存有限,但我沒想到;) 在包 numpy 中,您還可以選擇函數。
最后,您可以使用布爾表達式進行計數。
Result = numpy.random.choice(["head", "tail"], 100)
print(Result)
Numbe_of_head = (Result == "head").sum()
print(Number_of_head)
此外,此解決方案使用 numpy 及其迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.