从列表中选择5个不同的元素? [英] Choose 5 different elements from a list?
本文介绍了从列表中选择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.
这篇关于从列表中选择5个不同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文