简体   繁体   中英

Select up to 5 random elements from list in python

Lets say I have:

In[2]: t = [1,2,3]
In[3]: import random
In[4]: random.sample(t,2)
Out[4]: [1, 3]

How do I Select UP TO 5 unique random elements? I tried:

In[5]: random.sample(t,5)

but this gives:

ValueError: sample larger than population

I would like to return all 3 element in the case of a list of only 3.

也许

random.sample(t, min([len(t), 5]))

Assuming that you want them chosen randomly and that new_list is already defined,

import random

new_list += random.sample(old_list, 5)

If new_list is not already defined, then you can just do

new_list = random.sample(old_list, 5)

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