简体   繁体   English

Python random.shuffle() 的第二个参数有什么作用?

[英]What does Python random.shuffle()'s second argument do?

According to the Python Documentation ,根据Python 文档

random.shuffle(x[, random]) random.shuffle(x[, 随机])

Shuffle the sequence x in place.将序列 x 就地打乱。 The optional argument random is a 0-argument function returning a random float in [0.0, 1.0);可选参数 random 是一个 0 参数 function 返回 [0.0, 1.0] 中的随机浮点数; by default, this is the function random().默认情况下,这是 function random()。

Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators;请注意,即使 len(x) 相当小,x 的排列总数也大于大多数随机数生成器的周期; this implies that most permutations of a long sequence can never be generated.这意味着永远无法生成长序列的大多数排列。

Even after reading this, I still don't understand what is the role of the "random" argument.即使读到这里,我仍然不明白“随机”参数的作用是什么。 Also, why on earth the argument form is (x[, random]), not (x, random)?另外,为什么论证形式是 (x[, random]) 而不是 (x, random)? what is that bracket and comma?那个括号和逗号是什么?

Sorry for the stupid question...抱歉这个愚蠢的问题...

The bracket and comma are just a standard documentation notation for saying "this parameter is optional".括号和逗号只是表示“此参数是可选的”的标准文档符号。 You wouldn't use the brackets when making the call.拨打电话时不会使用括号。

The documentation seems pretty clear.文档看起来很清楚。 You can provide your own random number function, if you want to.如果需要,您可以提供自己的随机数 function。 With shuffle, it's hard to come up with a good justification for this.对于 shuffle,很难为此找到一个好的理由。

By default, this:默认情况下,这个:

random.shuffle(lst)

is the same as是相同的

random.shuffle(lst, random.random)

Checking the source code for shuffle , we can see that shuffle iterates through the list and swaps each item in the list with another random item in the list.查看shuffle 的源代码,我们可以看到shuffle遍历列表并将列表中的每个项目与列表中的另一个随机项目交换。 The random function is used to get that random element with which to switch the current element. random function 用于获取用于切换当前元素的随机元素。

For example, if you set random to a function that always returns 0, each element will be swapped with the first element in the list:例如,如果将random设置为始终返回 0 的 function,则每个元素将与列表中的第一个元素交换:

from random import shuffle

l = [1, 2, 3, 4, 5]
shuffle(l, lambda: 0)
print(l)
>>> [2, 3, 4, 5, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM