从列表中弹出随机元素的最pythonic 方法是什么? [英] What is the most pythonic way to pop a random element from a list?

查看:25
本文介绍了从列表中弹出随机元素的最pythonic 方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个长度未知的列表 x,我想从中随机弹出一个元素,以便列表之后不包含该元素.什么是最 Pythonic 的方式来做到这一点?

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?

我可以使用 poprandom.randintlen 的相当不方便的组合来实现,并且希望看到更短或更好的解决方案:

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.

推荐答案

你似乎在做的事情一开始看起来并不是很 Pythonic.你不应该从列表中间删除东西,因为在我知道的所有 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).

这篇关于从列表中弹出随机元素的最pythonic 方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆