Choose 5 different elements from a list?
What is the best way to choose 5 different elements from a python list and add开发者_JS百科 them to a new list?
Thanks for the help!
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)
If you don't want to change new_list
but want to instead create new_new_list
, then
new_new_list = new_list + random.sample(old_list, 5)
Now references to new_list
will still access a list without the five new elements but new_new_list
will reference a list with the five elements.
Use random.sample
call
import random
random.sample(yourlist,5)
You may need to be more specific, but to return 5 unique elements from your list you can simply use sample
from the random module
import random
num = 5
aList = range(30)
newList = []
newList+=random.sample(aList, num)
>>> list = [1,3,6,3,2,5,7,4,7,8,9,4,3,2,4,6,7]
>>> newlist = []
# Pick 5 and add to new list:
>>> newlist.extend(list[:5])
>>> newlist
[1, 3, 6, 3, 2]
精彩评论