random.shuffle()改变了x
list in place.
就地改变结构的 Python API 方法通常会返回None
,而不是修改后的数据结构。
>>> x = ['foo', 'bar', 'black', 'sheep']
>>> random.shuffle(x)
>>> x
['black', 'bar', 'sheep', 'foo']
如果你想创建一个new基于现有列表的随机洗牌列表,其中现有列表保持有序,您可以使用random.sample()输入的完整长度:
random.sample(x, len(x))
你也可以使用sorted() with random.random()对于排序键:
shuffled = sorted(x, key=lambda k: random.random())
但这会调用排序(O(N log N) 操作),而采样到输入长度只需要 O(N) 操作(与random.shuffle()
使用,从收缩池中交换随机值)。
Demo:
>>> 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']