为什么删除(x)不起作用?

时间:2014-10-12 15:43:48

标签: python while-loop coin-flipping

我试图制作一个简单的功能,在这个例子中掷硬币n次,五十(50)次,然后将结果存储到列表中my_list&#39 ;。使用for loop投掷Tosses。

如果投掷的结果不是25个头和25个尾(即24-26个比例),它应该删除包含结果的列表my_list的内容并再次循环50次,直到结果准确25-25。

功能:

  1. 打印空列表。
  2. 如果my_list.count(1)为25,则启动仅结束的while循环。
  3. 使用随机(1,2)投掷硬币。
  4. 将结果输入my_list。
  5. 如果my_list.count(1)不完全是25,那么代码应该删除列表中的内容并重复while循环。
  6. - - 编码: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;存储为intstr列表。我的猜测是在str

    我做错了什么?

2 个答案:

答案 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)仅删除xlist的第一次出现。我只是在每次迭代中使用一个新的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条件相同,但可读性较差。