我正在尝试编写一个程序来创建一个模拟翻转硬币的游戏。我想问用户应该扔多少次硬币。根据响应,程序应选择指定次数为0(头)或1(尾)的数字。我想要它打印这样的东西:“[头,尾,'头','头']:有3个头和2个尾巴”
到目前为止,这是我的代码:
import random
#this function creates a game that simulates a coin
#I will ask how many times that the coin should be tossed
def coinToss():
number = input("How many times do you want to flip the coin?: ")
myList = []
counter = 0
for element in range(number):
flip = random.randint(0, 1)
if flip == 0:
myList.append("Heads")
else:
myList.append("Tails")
print(str(myList)) + str(":there were ") + str(counter) + str(" Heads ") + str(" and ") + str(counter) + str(" Tails")
我有我的变量计数器,但如何添加头部和尾部?非常困惑。对不起,如果这听起来很容易。我知道我的印刷品最终会出错。
答案 0 :(得分:3)
不是将"heads"
或"tails"
追加到myList
,而是添加数字:
for element in range(number):
flip = random.randint(0, 1)
myList.append(flip)
现在,当您转到打印声明时,可以使用sum()
和len()
:
print "There were {} heads and {} tails".format(len(myList) - sum(myList), sum(myList))
由于您的列表将包含[0, 1, 1, 0, 1, 0, 0]
(示例)之类的内容,因此长度减去总和将为您提供零(头)的数量,而获得总和将为您提供数量(尾部) )。
使用字符串格式更简洁:)
答案 1 :(得分:0)
这应该对你有用
myList.count("Heads")
答案 2 :(得分:0)
import random
def coinToss():
numToss = input("How many times do you want to flip the coin?: ")
tossList = []
for element in range(number):
flip = random.randint(0, 1)
if flip == 0:
tossList.append("Heads")
else:
tossList.append("Tails")
print tossList, ": there were %d heads and %d tails" %(tossList.count("Heads"), tossList.count("Tails"))
或
def coinToss():
numToss = input("How many times do you want to flip the coin?: ")
tossList = []
headCounter = 0
for element in range(number):
flip = random.randint(0, 1)
if flip == 0:
tossList.append("Heads")
headCounter += 1
else:
tossList.append("Tails")
print tossList, ": there were %d heads and %d tails" %(headcounter, len(tossList)-headCounter)
或
def coinToss():
numToss = input("How many times do you want to flip the coin?: ")
tossList = []
for element in range(number):
tossList.append(random.randint(0, 1))
print tossList, ": there were %d heads and %d tails" %(tossList.count(1), tossList.count("Tails"))
或
def coinToss():
numToss = input("How many times do you want to flip the coin?: ")
tossList = []
for element in range(number):
tossList.append(random.randint(0, 1))
print tossList, ": there were %d heads and %d tails" %(sum(tossList), tossList.count("Tails"))
或
def coinToss():
numToss = input("How many times do you want to flip the coin?: ")
tossList = [random.randint(0, 1) for _ in xrange(numToss)]
print tossList, ": there were %d heads and %d tails" %(sum(tossList), tossList.count("Tails"))
或
def coinToss():
tossList = [random.randint(0, 1) for _ in xrange(input("How many times do you want to flip the coin?: "))]
print tossList, ": there were %d heads and %d tails" %(sum(tossList), tossList.count("Tails"))