Select up to 5 random elements from list in python

时间:2015-07-28 16:47:58

标签: 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.

2 个答案:

答案 0 :(得分:3)

maybe

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

答案 1 :(得分:2)

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)