为什么 random.shuffle 返回 None?
- 2024-12-17 08:30:00
- admin 原创
- 124
问题描述:
为什么在 Python 中random.shuffle
返回None
?
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> print shuffle(x)
None
我如何获取改组后的值而不是None
?
解决方案 1:
random.shuffle()
就地改变x
列表。
就地改变结构的 Python API 方法通常会返回None
,而不是修改后的数据结构。
>>> x = ['foo', 'bar', 'black', 'sheep']
>>> random.shuffle(x)
>>> x
['black', 'bar', 'sheep', 'foo']
如果您想基于现有列表创建一个新的随机打乱列表,其中现有列表保持顺序,则可以使用random.sample()
输入的全长:
random.sample(x, len(x))
您还可以使用sorted()
withrandom.random()
作为排序键:
shuffled = sorted(x, key=lambda k: random.random())
但这会调用排序(O(N log N)操作),而对输入长度进行采样仅需要 O(N)操作(与random.shuffle()
使用的过程相同,从缩小的池中交换出随机值)。
演示:
>>> 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']
解决方案 2:
此方法也有效。
import random
shuffled = random.sample(original, len(original))
解决方案 3:
到底是为什么呢?
效率
shuffle
就地修改列表。这很好,因为如果您不再需要原始列表,复制大型列表将是纯粹的开销。
Python 风格
根据Python 风格的“显式优于隐式”原则,返回列表不是一个好主意,因为人们可能会认为这是一个新的列表,但事实上并非如此。
但我不喜欢这样!
如果你确实需要一份新的清单,你必须写类似
new_x = list(x) # make a copy
random.shuffle(new_x)
这非常明确。如果您经常需要这个习语,请将其包装在一个返回的函数中shuffled
(请参阅) 。sorted
`new_x`
解决方案 4:
根据文档:
将序列 x 原地打乱。可选参数 random 是一个 0 参数函数,返回 [0.0, 1.0) 中的随机浮点数;默认情况下,这是函数 random()。
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> shuffle(x)
>>> x
['bar', 'black', 'sheep', 'foo']
解决方案 5:
我对这个概念有过这样的顿悟:
from random import shuffle
x = ['foo','black','sheep'] #original list
y = list(x) # an independent copy of the original
for i in range(5):
print shuffle(y) # shuffles the original "in place" prints "None" return
print x,y #prints original, and shuffled independent copy
>>>
None
['foo', 'black', 'sheep'] ['foo', 'black', 'sheep']
None
['foo', 'black', 'sheep'] ['black', 'foo', 'sheep']
None
['foo', 'black', 'sheep'] ['sheep', 'black', 'foo']
None
['foo', 'black', 'sheep'] ['black', 'foo', 'sheep']
None
['foo', 'black', 'sheep'] ['sheep', 'black', 'foo']
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD