Python 从循环中计算结果?

Python 从循环中计算结果?,python,count,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

创建了一个程序,将硬币翻转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))
#一个将硬币翻转100次并每次告诉你结果的程序
随机输入
计数器=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))
heads=0
计数器=0
翻转=[“真”、“假”]

计数器如果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))
这是我的照片

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

这并不像理解那么清晰,但即使你来自另一种语言,也很容易理解这里发生的事情。

sum(random.choice((1,0))for x in range(100))

你可能还想看看:



你忘了带
其他的
。另外,你想要的是
=
,而不是
=
。不,我没有
else
是可选的,如果翻转结果为
false
,我不想增加计数器或任何东西。不过,我同意
==
。正如我说的,我已经生锈了。我刚刚阅读了文档并修复了它。再给两个计数器:
counter t
counter
,然后将
random.choice(flip)
的值存储在名为
RandomV
的变量中。如果
RandomV==true
{++counter}或者{++counter}不需要括号:),因为可以在生成器表达式上调用sum()
print sum(random.choice([0,1]),用于范围(100)内的x
--最好省略方括号,因为在这种情况下不会创建中间列表。实际上不是
random.random(0,100)
给出一个介于0和100之间的数字。我想要100个1或0。你几乎是对的
random。randint(1100)
将是答案,因为两个边界都包含在内,我们需要做100次,100是正面或反面的最大值。其他建议不是那么简单吗<代码>随机。randint(01100)
包含两个边界
random。randrange(01100)
排除上边界。如果您想尝试100次,其中0为最小值,100为最大值,那么这些方法都不起作用。
>>> import random
>>> sides = ['heads', 'tails']
>>> headsc = tailsc = 0
>>> for _ in xrange(100):
...     if random.choice(sides) == 'heads':
...         headsc += 1
...     else:
...         tailsc += 1
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})