我试图制作一个简单的功能,在这个例子中掷硬币n次,五十(50)次,然后将结果存储到列表中my_list
&#39 ;。使用for loop
投掷Tosses。
如果投掷的结果不是25个头和25个尾(即24-26个比例),它应该删除包含结果的列表my_list
的内容并再次循环50次,直到结果准确25-25。
- - 编码:latin-1 - -
import random
def coin_tosser():
my_list = []
# check if there is more or less 1 (heads) in the list
# if there is more or less number ones in the list, loop
# "while". If "coin tosser" throws exactly 25 heads and
# 25 tails, then "while my_list.count(1) != 25:" turns True
while my_list.count(1) != 25: # check if there is more or less 1 (heads) in the list
print "Throwing heads and tails:"
for i in range(50):
toss = random.randint(int(1),int(2)) #tried this also without int() = (1,2)
my_list.append(toss)
if my_list.count(1) < 25 or my_list.count(1) > 25:
my_list.remove(1) # remove number ones (heads) from the list
my_list.remove(2) # remove number twos (tails) from the list
# after loop is finished (25 number ones in the list), print following:
print "Heads is in the list",
print my_list.count(1), "times."
print "Tails is in the list",
print my_list.count(2), "times."
# print
print my_list
coin_tosser()
当我尝试使用my_list.remove(1)时,它不会从列表中删除任何内容。如果我将my_list.remove(1)替换为my_list.remove(&#39; test&#39;)并添加&#39; test&#39;到my_list,如果条件不满足,程序将删除&#39; test&#39 ;.
为什么它不删除数字?我不确定这些&#34; 1&#34;和&#34; 2&#34;存储为int
或str
列表。我的猜测是在str
我做错了什么?
答案 0 :(得分:0)
list.remove(x)
仅删除与x
相等的第一个项目,因此您每次只删除一个项目:
my_list.remove(1)
my_list.remove(2)
因此,您根本不清除列表。相反,您可以通过将列表设置为新的空列表来完全清除列表:
my_list = []
由于你只对头/尾投掷的数量感兴趣,你也可以计算它们,而不是记住所有单独的投掷。所以你只需要一个柜台:
headCount = 0
while headCount != 25:
print "Throwing heads and tails:"
headCount = 0
for i in range(50):
toss = random.randint(1, 2)
if toss == 1:
headCount += 1
答案 1 :(得分:0)
正如@poke所述,list.remove(x)
仅删除x
中list
的第一次出现。我只是在每次迭代中使用一个新的my_list
列表,并摆脱循环内的整个if
。
while my_list.count(1) != 25: # check if there is more or less 1 (heads) in the list
print "Throwing heads and tails:"
my_list = []
for i in range(50):
toss = random.randint(int(1),int(2)) #tried this also without int() = (1,2)
my_list.append(toss)
如果您在循环中有25个头,则不需要再次检查,因为您只是在循环条件while my_list.count(1) != 25
BTW:
my_list.count(1) < 25 or my_list.count(1) > 25
与您的while
条件相同,但可读性较差。