从循环中计算结果?

时间:2013-05-28 12:52:30

标签: python count

创建了一个程序,该程序翻转一次硬币100次并每次给出随机结果。只是想知道是否可以计算每个结果出现的次数。不知道从哪里开始。我到目前为止......

# A program which flips a coin 100 times and tells you the outcome each time

import random

counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    print (random.choice(flip))

6 个答案:

答案 0 :(得分:7)

如果1表示头部,则表示头部数量:

import random
print sum(random.choice([0,1]) for x in range(100))
# or more verbose:
print sum('heads' == random.choice(['heads','tails']) for x in range(100))

答案 1 :(得分:2)

这是我的看法

heads=0
tails=0
for i in range(100):
  if random.randrange(2) == 0:
      heads+=1
  else:
      tails+=1

这并不像理解那么干净,但即使你来自另一种语言,也很容易理解这里发生了什么。

答案 2 :(得分:2)

对于范围(100)中的x,求和(random.choice((1,0))

答案 3 :(得分:2)

您可能还想查看collections.Counter

Docstring:
Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

In [1]: import random

In [2]: from collections import Counter

In [3]: Counter(random.choice(('heads','tails')) for _ in range(100))
Out[3]: Counter({'heads': 51, 'tails': 49})

答案 4 :(得分:1)

>>> import random
>>> sides = ['heads', 'tails']
>>> headsc = tailsc = 0
>>> for _ in xrange(100):
...     if random.choice(sides) == 'heads':
...         headsc += 1
...     else:
...         tailsc += 1

答案 5 :(得分:0)

像这样:

heads = 0
counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    result = random.choice(flip))
    if result == "true":
        heads = heads+1
    print (result)
print ("heads: " + heads)
print ("tails: " + (99 - heads))

实际上我的Python生锈了,所以我不知道我的语法是否正确,但它应该是接近的。