从列表中选择5个不同的元素?
问题描述:
从python列表中选择5个不同元素并将其添加到新列表的最佳方法是什么?
What is the best way to choose 5 different elements from a python list and add them to a new list?
感谢您的帮助!
答
假定您希望它们是随机选择的,并且已经定义了new_list
,
Assuming that you want them chosen randomly and that new_list
is already defined,
import random
new_list += random.sample(old_list, 5)
如果尚未定义new_list
,则可以执行
If new_list
is not already defined, then you can just do
new_list = random.sample(old_list, 5)
如果您不想更改new_list
,而是想创建new_new_list
,则
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)
现在对new_list
的引用仍将访问没有五个新元素的列表,但是new_new_list
将引用具有五个元素的列表.
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.