Python-为什么random.shuffle返回None?
为什么要用Python random.shuffle
返回None
?
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> print shuffle(x)
None
我如何获得改组后的值而不是None
?
-
random.shuffle()
更改x列表到位。就地更改结构的
Python API
方法通常返回None,而不是修改后的数据结构。如果要基于现有列表创建新的随机混排列表,并按顺序保留现有列表,则可以使用
random.sample()
输入的完整长度:x = ['foo', 'bar', 'black', 'sheep'] random.sample(x, len(x))
你还可以将
sorted()with random.random()
用于排序键:shuffled = sorted(x, key=lambda k: random.random())
但这会调用排序(
O(NlogN)
操作),而采样到输入长度仅需要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']