为什么 random.shuffle 返回 None ? [英] Why does random.shuffle return None?

查看:25
本文介绍了为什么 random.shuffle 返回 None ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 random.shuffle 在 Python 中返回 None?

<预><代码>>>>x = ['foo','bar','black','sheep']>>>从随机导入随机播放>>>打印洗牌(x)没有任何

如何获得混洗后的值而不是 None?

解决方案

random.shuffle() 更改 x 列表就地.

就地更改结构的 Python API 方法通常返回 None,而不是修改后的数据结构.

<预><代码>>>>x = ['foo', 'bar', 'black', 'sheep']>>>random.shuffle(x)>>>X['黑色','酒吧','羊','富']


如果您想根据现有列表创建一个随机打乱列表,其中现有列表按顺序排列,您可以使用 random.sample() 输入的全长:

random.sample(x, len(x))

您也可以使用 sorted()random.random() 用于排序键:

shuffled = sorted(x, key=lambda k: random.random())

但这会调用排序(O(N log N) 操作),而对输入长度的采样只需要 O(N) 操作(使用与 random.shuffle() 相同的过程,从收缩池中换出随机值).

演示:

<预><代码>>>>随机导入>>>x = ['foo', 'bar', 'black', 'sheep']>>>随机样本(x,len(x))['bar', 'sheep', 'black', 'foo']>>>sorted(x, key=lambda k: random.random())['羊','富','黑色','酒吧']>>>X['foo', 'bar', 'black', 'sheep']

Why is random.shuffle returning None in Python?

>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> print shuffle(x)
None

How do I get the shuffled value instead of None?

解决方案

random.shuffle() changes the x list in place.

Python API methods that alter a structure in-place generally return None, not the modified data structure.

>>> x = ['foo', 'bar', 'black', 'sheep']
>>> random.shuffle(x)
>>> x
['black', 'bar', 'sheep', 'foo']


If you wanted to create a new randomly-shuffled list based on an existing one, where the existing list is kept in order, you could use random.sample() with the full length of the input:

random.sample(x, len(x))     

You could also use sorted() with random.random() for a sorting key:

shuffled = sorted(x, key=lambda k: random.random())

but this invokes sorting (an O(N log N) 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).

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']

这篇关于为什么 random.shuffle 返回 None ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆