Warm tip: This article is reproduced from serverfault.com, please click

Python

发布于 2020-11-28 05:33:17

When you use shuffle(x, random), you have two parameters: the list and the function. By default, the function is random(), which returns a random value between 0 and 1.

Now, what I would like to know is, how does this affect the list? If, for example, I assign a function to return a specific value in such way like the following:

import random

def myfunction():
  return 0.1

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

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

What will happen? From what I've seen, the way the list is organized changes. So, If I, once again, determine the value the function returns, will It be organized differently?

import random

def myfunction():
  return 0.9

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

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

Whereas If return a value such as 0.89, the way the list is organized does not change. This leads to my doubt.

I probably made some vague assumptions, but It's the best explanation I have.

Questioner
Nameless
Viewed
0
Sash Sinha 2020-11-28 13:55:02

I wouldn't worry about the random argument or use it in any new code as it has been deprecated in Python 3.9:

random.shuffle(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.

If you are interested in how it works anyway here is the actual source code that makes it pretty clear:

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]