Shuffle the sequence x in place. The optional argument random is a
0-argument function returning a random float in [0.0, 1.0); by
default, this is the function random().
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> shuffle(x)
>>> x
['bar', 'black', 'sheep', 'foo']
这个方法也有效。
根据docs:
random.shuffle()
更改x
列表的位置。就地更改结构的Python API方法通常返回
None
,而不是修改后的数据结构。如果要创建一个基于现有列表的随机洗牌列表,其中现有列表保持顺序,则可以使用^{} 输入的完整长度:
您还可以将^{} 与^{} 一起用于排序键:
但这会调用排序(O(NlogN)操作),而对输入长度的采样只需要O(N)操作(使用与
random.shuffle()
相同的过程,从收缩池中交换随机值)。演示:
相关问题 更多 >
编程相关推荐