lundi 26 octobre 2015

In Python, how can I randomly chose an element of one list that's NOT in a second list?

Say I have a list2 of randomly chosen elements from a large list1. Is there a clever way of choosing an element from list1 that's NOT already in list2?

For example:

list1 = range(20,100)
list2 = [37,49,22,35,72] # could be much longer

while True:
    n = random.choice(list1)
    if n not in list2:
        break

# now n is an element of list1 that's not in list2

I feel like there must be a more efficient way of doing this than a guess-and-check while-loop.




Aucun commentaire:

Enregistrer un commentaire