Given several lists
l = [[1,2,3,4,5],[1,6,7,8],[2,3,4],[1,9,10,13]]
Is there an easy method to randomly pick a list that contains 1 using random.choice? I tried simple codes like
random.choice(1 in l)
or
random.choice(l, 1=True), but none of them work.
There is no built-in method (that would be pretty niche) but you can do the following:
import random
my_lists = [[1,2,3,4,5],[1,6,7,8],[2,3,4],[1,9,10,13]]
random_list = random.choice([sublist for sublist in my_lists if 1 in sublist])
or using filter:
random_list = random.choice(list(filter(lambda sublist: 1 in sublist, my_lists)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With