Why does remove(x) not work?
我尝试了一个简单的函数,在这个例子中,将硬币抛n次,50次,然后将结果存储到"EDOCX1"(0)列表中。抛掷使用
如果抛出的结果不是25个头部和25个尾部(即24-26个比率),则应删除包含结果的列表
--编码:拉丁语-1--
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 my_list coin_tosser() |
问题
当我尝试使用我的_list.remove(1)时,它不会从列表中删除任何内容。如果我用我的"list.remove"(测试)替换"list.remove"(1)并将"test"(测试),然后将"test"(测试)添加到我的"list"(测试),那么如果不满足条件(应该如此),程序将删除"test"(测试)。
为什么不删除数字?我不确定这些"1"和"2"是否存储为列表中的
我做错了什么?
如@poke所述,
1 2 3 4 5 6 | 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个磁头,则无需再次检查,因为您只是在循环条件
顺便说一句:
1 | my_list.count(1) < 25 or my_list.count(1) > 25 |
与您的
1 2 | my_list.remove(1) my_list.remove(2) |
因此,你根本不清除你的清单。相反,只需将列表设置为新的空列表,即可完全清除列表:
1 | my_list = [] |
号
由于您只对头部/尾部投掷次数感兴趣,因此您也可以对其进行计数,而不是记住所有单个投掷。所以你只有一个柜台:
1 2 3 4 5 6 7 8 | 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 |