繁体   English   中英

如何计算从列表中打印特定值的次数?

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

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