Python - 使用 shuffle 时参数 'function' 如何影响列表

Python - How does argument 'function' affect a list when using shuffle

当您使用 shuffle(x, random) 时,您有两个参数:列表和函数。默认情况下,该函数是 random(),其中 return 是 0 到 1 之间的随机值。

现在,我想知道的是,这对列表有何影响?例如,如果我以如下方式将函数分配给 return 特定值:

import random

def myfunction():
  return 0.1

mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist, myfunction)

print(mylist) #Prints: ['banana', 'cherry', 'apple']

会发生什么?据我所见,列表的组织方式发生了变化。所以,如果我再次确定函数 returns 的值,它的组织方式会有所不同吗?

import random

def myfunction():
  return 0.9

mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist, myfunction)

print(mylist) #Prints: ['apple', 'banana', 'cherry']

而如果 return 是 0.89 之类的值,则列表的组织方式不会改变。这就引出了我的疑问。

我可能做了一些模糊的假设,但这是我能得到的最好的解释。

我不会担心 random 参数或在任何新代码中使用它,因为它已在 Python 3.9:

中弃用

random.<b>shuffle</b>(x[, random])

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().

...

Deprecated since version 3.9, will be removed in version 3.11: The optional parameter random.

如果您对它的工作原理感兴趣,这里是实际的 source code,它非常清楚:

def shuffle(self, x, random=None):
        """Shuffle list x in place, and return None.
        Optional argument random is a 0-argument function returning a
        random float in [0.0, 1.0); if it is the default None, the
        standard random.random will be used.
        """

        if random is None:
            randbelow = self._randbelow
            for i in reversed(range(1, len(x))):
                # pick an element in x[:i+1] with which to exchange x[i]
                j = randbelow(i + 1)
                x[i], x[j] = x[j], x[i]
        else:
            _warn('The *random* parameter to shuffle() has been deprecated\n'
                  'since Python 3.9 and will be removed in a subsequent '
                  'version.',
                  DeprecationWarning, 2)
            floor = _floor
            for i in reversed(range(1, len(x))):
                # pick an element in x[:i+1] with which to exchange x[i]
                j = floor(random() * (i + 1))
                x[i], x[j] = x[j], x[i]