从列表中弹出随机元素的最Python方式是什么? [英] What is the most pythonic way to pop a random element from a list?
问题描述
说我有一个长度未知的列表x
,我想从该列表中随机弹出一个元素,以便此后列表中不包含该元素.最Python的方法是什么?
Say I have a list x
with unkown length from which I want to randomly pop one element so that the list does not contain the element afterwards. What is the most pythonic way to do this?
我可以使用pop
,random.randint
和len
的组合来方便地做到这一点,并且希望看到更短或更佳的解决方案:
I can do it using a rather unhandy combincation of pop
, random.randint
, and len
, and would like to see shorter or nicer solutions:
import random
x = [1,2,3,4,5,6]
x.pop(random.randint(0,len(x)-1))
我要实现的目标是从列表中连续弹出随机元素. (即,随机弹出一个元素并将其移至字典,随机弹出另一个元素并将其移至另一字典,...)
What I am trying to achieve is consecutively pop random elements from a list. (i.e., randomly pop one element and move it to a dictionary, randomly pop another element and move it to another dictionary, ...)
请注意,我使用的是Python 2.6,没有通过搜索功能找到任何解决方案.
Note that I am using Python 2.6 and did not find any solutions via the search function.
推荐答案
乍一看,您似乎想要做的似乎不太像Python.您不应该从列表的中间删除内容,因为列表在我所知道的所有Python实现中都是作为数组实现的,所以这是一个O(n)
操作.
What you seem to be up to doesn't look very Pythonic in the first place. You shouldn't remove stuff from the middle of a list, because lists are implemented as arrays in all Python implementations I know of, so this is an O(n)
operation.
如果您确实需要将此功能作为算法的一部分,则应签出类似 blist
支持从中间有效删除.
If you really need this functionality as part of an algorithm, you should check out a data structure like the blist
that supports efficient deletion from the middle.
在纯Python中,如果不需要访问其余元素,该怎么办就是先将列表随机播放,然后对其进行遍历:
In pure Python, what you can do if you don't need access to the remaining elements is just shuffle the list first and then iterate over it:
lst = [1,2,3]
random.shuffle(lst)
for x in lst:
# ...
如果您确实需要剩余部分(有点代码味道,恕我直言),至少您现在可以从列表末尾pop()
(很快!):
If you really need the remainder (which is a bit of a code smell, IMHO), at least you can pop()
from the end of the list now (which is fast!):
while lst:
x = lst.pop()
# do something with the element
通常,如果您使用更具功能性的样式,而不是突变状态(就像对列表所做的那样),通常可以使程序更优雅地表达.
In general, you can often express your programs more elegantly if you use a more functional style, instead of mutating state (like you do with the list).
这篇关于从列表中弹出随机元素的最Python方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!