简体   繁体   中英

Randomly choosing from multiple lists in python

I have 3 lists and want a way that Python chooses multiple options from all lists. How can I do this?

I've tried the code below, but it only gives me 1 option in total.

list_1 = [1,3,5]

list_2 = [2,4,6]

list_3 = [10]

random.choice([random.choice(list_1)] + [random.choice(list_2)] + 
              [random.choice(list_3)])

Your question isn't clear but from what I think you are trying to ask:

To make a random choice from a few lists, you could try this:

list_1 = [1,3,5]

list_2 = [2,4,6]

list_3 = [10]

random.choice([random.choice(list_1), random.choice(list_2), random.choice(list_3)])

you can use the random.sample function to retrieve multiple random values

syntax : random.sample(list,k) where k is the number of values to be sampled.

list_1 = [1,3,5]

list_2 = [2,4,6]

list_3 = [10]

random.sample(list_1+list_2+list_3,3)

[edit]

if you want one from each list,

final_list = random.sample(list_1,1)+random.sample(list_2,1)+random.sample(list_3,1)

this can be done using random.choice as below

final_list =[ random.choice(list_1),random.choice(list_2),random.choice(list_3)]

Do you mean something like this:

list_1 = [1,3,5]
list_2 = [2,4,6]   
list_3 = [10]

[random.choice(list_1)+random.choice(list_2)+random.choice(list_3)]

this would give:

 [1,6,10]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM