简体   繁体   English

list.remove(x): x 不在随机数列表中

[英]list.remove(x): x not in list on a random number list

I am getting list.remove(x) error So what am I doing here is that, am using this program to generate random numbers without duplicates from a set range and removing the number as the number has been called but somehow I am getting not in the list message even though the random has been called from the list.我收到list.remove(x)错误所以我在这里做的是,我正在使用这个程序从设定的范围内生成不重复的随机数,并在调用该数字时删除该数字,但不知何故我没有进入即使从列表中调用了随机数,列表消息也是如此。

import random
def checkPizza(numOfPizza):
    pizzaD = []
    allowed_val = list(range(0,M+1))
    if numOfPizza == 2:
        allowed_val = allowed_val
        while True:
            allowed_val = allowed_val
            alpha = random.choice(allowed_val)
            beta = random.choice(allowed_val)
            if alpha != beta:
                allowed_val.remove(alpha)
                allowed_val.remove(beta)
                pizzaD.append(alpha)
                pizzaD.append(beta)
                break

Your code runs fine for me.你的代码对我来说运行良好。 You did not define M here so I chose an arbitrary number:你没有在这里定义 M 所以我选择了一个任意数字:

import random
def checkPizza(numOfPizza):
    pizzaD = []
    allowed_val = list(range(0,10))
    if numOfPizza == 2:
        allowed_val = allowed_val
        while True:
            allowed_val = allowed_val
            alpha = random.choice(allowed_val)
            beta = random.choice(allowed_val)

            if alpha != beta:
                allowed_val.remove(alpha)
                allowed_val.remove(beta)
                pizzaD.append(alpha)
                pizzaD.append(beta)
                print(pizzaD)
                break


checkPizza(2)

output: output:

[7, 5]

It is howevery not clear for me what allowed_val=allowed_val is suppose to do.然而,我不清楚allowed_val=allowed_val应该做什么。 It appears twice in your code.它在您的代码中出现两次。 Also I think you are using a while loop for the case that alpha equals beta.此外,我认为您正在使用 while 循环来处理 alpha 等于 beta 的情况。 In my opinion the following would be prefered:在我看来,以下是首选:

alpha,beta = random.sample(allowed_val,2)

This will asign two values from the list of allowed_val that are not the same.这将从 allowed_val 列表中分配两个不相同的值。 In this case you do not need the while True loop在这种情况下,您不需要while True循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM