Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
53 views
in Technique[技术] by (71.8m points)

python - 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.

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
question from:https://stackoverflow.com/questions/65829385/list-removex-x-not-in-list-on-a-random-number-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code runs fine for me. You did not define M here so I chose an arbitrary number:

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:

[7, 5]

It is howevery not clear for me what allowed_val=allowed_val is suppose to do. It appears twice in your code. Also I think you are using a while loop for the case that alpha equals 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. In this case you do not need the while True loop


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...