rrr
rrr

Reputation: 371

Randomly pick a list that contains the specific element

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.

Upvotes: 3

Views: 84

Answers (2)

Selcuk
Selcuk

Reputation: 59444

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)))

Upvotes: 5

Amit Yadav
Amit Yadav

Reputation: 5014

Try the below code:

Get all the sublists containing 1, and randomly return one.

import random

a_list = [[1,2,3,4,5],[1,6,7,8],[2,3,4],[1,9,10,13]]

lists_with_element = [sub_list for sub_list in a_list if 1 in sub_list]

if len(lists_with_element):
    print(lists_with_element[random.randint(0, len(lists_with_element)-1)])
else:
    print("There is no list containing 1")

EDIT: The above condition will avoid the error if no sublist contains 1 I hope it helps.

Upvotes: 0

Related Questions