【问题标题】:Python - How does argument 'function' affect a list when using shufflePython - 使用随机播放时参数“函数”如何影响列表
【发布时间】:2020-11-28 05:33:17
【问题描述】:

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

现在,我想知道的是,这对列表有何影响?例如,如果我指定一个函数以如下方式返回特定值:

import random

def myfunction():
  return 0.1

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

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

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

import random

def myfunction():
  return 0.9

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

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

而如果返回 0.89 之类的值,则列表的组织方式不会改变。这引起了我的怀疑。

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

【问题讨论】:

    标签: python random shuffle


    【解决方案1】:

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

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

    随机播放序列x

    可选参数 random 是一个 0 参数函数,返回一个 [0.0, 1.0) 中的随机浮点数;默认情况下,这是函数random()

    ...

    自 3.9 版起已弃用,将在 3.11 版中移除:可选参数 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]
    

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多