从随机数列表中计数的问题

2024-09-28 22:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我决定在圣诞假期用我的锉刀学习python。你知道吗

我正在运行Python 2.7,在我正在进行的书中的一个练习中,我尝试编写一个抛硬币程序,将硬币抛100次,然后打印每次抛硬币的结果和头尾的总数。你知道吗

程序生成每次投掷的结果,并在100圈后停止。你知道吗

这是我一直坚持的计数。你知道吗

我的代码是:

import random

print ("Welcome to the coin toss simulator")
start = raw_input("Would you like to start: ")

if start == "y":

        count = 0

        while count <= 100:
                outcome = random.randint(1, 2)
                count +=1
                if outcome == 1:
                        print("Heads")
                else:
                        print("Tails")

print("You tossed: ", outcome.count(1), " Heads")
print("You tossed: ", outcome.count(2), " Tails")

input("\n\nPress the enter key to exit.")

我收到的错误消息是:

Traceback (most recent call last):
  File "./coin_toss.py", line 23, in <module>
    print("You tossed: ", outcome.count(1), " Heads")
AttributeError: 'int' object has no attribute 'count'

Tags: theto程序youinputcount硬币random
3条回答

您得到的实际错误仅仅是因为random.randint()返回一个整数(因为那会做什么呢?)。然后,在最后的print调用中,尝试调用这个整数的count()方法,但是整数没有count()方法。你知道吗

我建议把头尾分开记录。例如:

if outcome == 1:
    heads_count += 1
else:
    tails_count += 1

您可以使用Python提供的高性能Counter数据容器:

import random
from collections import Counter

print ("Welcome to the coin toss simulator")
start = raw_input("Would you like to start: ")
c = []

if start == "y":

        count = 0

        while count <= 100:
                outcome = random.randint(1, 2)
                count +=1
                if outcome == 1:
                        print("Heads")
                else:
                        print("Tails")
                c.append(outcome)
count = Counter(c)
print("You tossed: ", count[1], " Heads")
print("You tossed: ", count[2], " Tails")

input("\n\nPress the enter key to exit.")

outcome是投币的结果。你找不到在1中有多少1;这没有意义。您必须将结果保存在某处,例如list。然后可以计算其中每个数字的出现次数:

        outcome = [] # initialize the list
        while count <= 100:
                outcome.append(randint(1, 2)) # add the result to the list
                count +=1
                if outcome[-1] == 1: # check the last element in the list
                        print("Heads")
                else:
                        print("Tails")

print("You tossed: ", outcome.count(1), " Heads") # now these work
print("You tossed: ", outcome.count(2), " Tails")

相关问题 更多 >