简体   繁体   中英

How to take random samples from different lists and combine them into a new list?

a = [1, 2, 3, 4, 5, 6]
b = [7, 8, 9, 0]

My goal is to randomly take 3 values from each list and combine them into one new list.

c = [1, 2, 3, 7, 8, 9]

With random.sample I can pick up values from one list at a time.

x = random.sample(a, 3)
y = random.sample(b, 3)

I could combine the results in several steps but I wonder if there is a cleaner version of this.

You could try using the list.extend() method:

import random

lists = [
    [1, 2, 3, 4, 5, 6],
    [7, 8, 9, 0]
]
samples = []
for i in lists:
    samples.extend(random.sample(i, 3))

Ok. I thought there would be a solution to pick up the values in a one-liner.

If you really need a one-liner...

[thing for x in (random.sample(q,3) for q in (a,b)) for thing in x]

Some prep then the one liner - please no groans.

>>> from functools import reduce,partial
>>> from operator import add
>>> reduce(add,map(partial(random.sample,**{'k':3}), (a,b)))
[2, 3, 6, 7, 0, 8]
>>>    # or
>>> reduce(add,map(lambda w: random.sample(w,3), (a,b)))

If you're looking for a one-liner...

import random
a = [1, 2, 3, 4, 5, 6]  # List a
b = [7, 8, 9, 0]  # List b
# If you want a one-liner, this should do
x, y = zip(*random.sample(list(zip(a, b)), 3))
c = list(x + y)  # Combining the two sample sets
print(c)

Ok, I found a solution that is acceptable for me:

a = [1, 2, 3, 4, 5, 6]
b = [7, 8, 9, 0]

c_first = [random.sample(a, 3), random.sample(b, 3)]

# Output [[1, 3, 5], [8, 7, 9]]

c_second = [item for sublist in c_first for item in sublist]

print(c_second)

Output:

[1, 3, 5, 8, 7, 9]

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