Home  >  Q&A  >  body text

Python 3.5 random.shuffle problem

When generating a random list, the random.shuffle() function is used. The following questions arise about the call of this function:
If a list is explicitly defined, such as li = [], the shuffle function It can produce the desired results;
But if list(range(n)) is used as the parameter of shuffle, None will be returned. As shown in the figure:

What's going on? They all belong to the list category

世界只因有你世界只因有你2711 days ago1215

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-18 10:50:52

    >>> help(random.shuffle)
    Help on method shuffle in module random:
    
    shuffle(x, random=None) method of random.Random instance
        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.

    It is mentioned in the document that if an list对象, 则直接作用鱼listobject

    is given
    >>> a = list(range(20))
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    >>> random.shuffle(a)
    
    >>> a  # a的值已改变
    [1, 6, 3, 15, 0, 5, 19, 10, 7, 18, 4, 2, 12, 14, 8, 16, 9, 11, 13, 17]
    >>>

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-18 10:50:52

    Because random.shuffle()会直接作用于list本身,而不会返回任何值,所以你第一个语句的结果会是None.但是在random.shuffle(li)的时候,你打印的是lithis list itself has been changed. If you write like this

    li = random.shuffle(li)

    Then it will return the same wayNone.所以想要得到list(range(20))shuffle操作过后的值,需要先给它一个变量名,在被shuffleYou can access it only after the operation.

    reply
    0
  • Cancelreply