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

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

问题描述

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

Why is random.shuffle returning None in Python?

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

如何获取改组后的值而不是None?

How do I get the shuffled value instead of None?

推荐答案

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

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

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

如果您想基于现有列表创建随机排序的 new 列表,并按顺序排列现有列表,则可以使用

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

x = ['foo', 'bar', 'black', 'sheep']
random.sample(x, len(x))     

您还可以将 sorted() random.random() 以获取排序键:

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

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

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

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

演示:

>>> 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天全站免登陆