为什么random.shuffle返回None? [英] Why does random.shuffle return None?
问题描述
为什么random.shuffle
在Python中返回None
?
Why is random.shuffle
returning None
in Python?
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> print shuffle(x)
None
如何获取改组后的值而不是None
?
How do I get the shuffled value instead of None
?
推荐答案
random.shuffle()
更改x
列表就地.
在原位更改结构的Python API方法通常返回None
,而不是修改后的数据结构.
Python API methods that alter a structure in-place generally return None
, not the modified data structure.
如果您想基于现有列表创建随机排序的 new 列表,并按顺序排列现有列表,则可以使用
If you wanted to create a new randomly-shuffled list based of an existing one, where the existing list is kept in order, you could use random.sample()
with the full length of the input:
x = ['foo', 'bar', 'black', 'sheep']
random.sample(x, len(x))
您还可以将 sorted()
与 random.random()
以获取排序键:
You could also use sorted()
with random.random()
for a sorting key:
shuffled = sorted(x, key=lambda k: random.random())
但这会调用排序(O(NlogN)操作),而采样到输入长度仅需要O(N)操作(使用与random.shuffle()
相同的过程,从收缩池中换出随机值).
but this invokes sorting (an O(NlogN) operation), while sampling to the input length only takes O(N) operations (the same process as random.shuffle()
is used, swapping out random values from a shrinking pool).
演示:
>>> import random
>>> x = ['foo', 'bar', 'black', 'sheep']
>>> random.sample(x, len(x))
['bar', 'sheep', 'black', 'foo']
>>> sorted(x, key=lambda k: random.random())
['sheep', 'foo', 'black', 'bar']
>>> x
['foo', 'bar', 'black', 'sheep']
这篇关于为什么random.shuffle返回None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!