Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly pick a list that contains the specific element

Tags:

python

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.

like image 554
rrr Avatar asked Feb 01 '26 03:02

rrr


1 Answers

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)))
like image 99
Selcuk Avatar answered Feb 02 '26 16:02

Selcuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!