Python - shuffle only some elements of a list

后端 未结 8 1513
礼貌的吻别
礼貌的吻别 2020-12-06 16:52

I\'m trying to shuffle only elements of a list on 3rd till last position so the 1st two will always stay in place e.g.

list = [\'a?\',\'b\',\'c\',\'d\',\'e\'         


        
8条回答
  •  执念已碎
    2020-12-06 17:51

    To shuffle a slice of the list in place, without copies, we can use a Knuth shuffle:

    import random
    def shuffle_slice(a, start, stop):
        i = start
        while (i < stop-1):
            idx = random.randrange(i, stop)
            a[i], a[idx] = a[idx], a[i]
            i += 1
    

    It does the same thing as random.shuffle, except on a slice:

    >>> a = [0, 1, 2, 3, 4, 5]
    >>> shuffle_slice(a, 0, 3)
    >>> a
    [2, 0, 1, 3, 4, 5]
    

提交回复
热议问题