Python - shuffle only some elements of a list

后端 未结 8 1511
礼貌的吻别
礼貌的吻别 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:41

    I copied the shuffle function from random.shuffle and adapted it, so that it will shuffle a list only on a defined range:

    import random
    a = range(0,20)
    b = range(0,20)
    
    def shuffle_slice(x, startIdx, endIdx):
        for i in reversed(xrange(startIdx+1, endIdx)):
           # pick an element in x[:i+1] with which to exchange x[i]
           j = random.randint(startIdx, i)
           x[i], x[j] = x[j], x[i]
    
    #Shuffle from 5 until the end of a
    shuffle_slice(a, 5, len(a))    
    print a
    
    #Shuffle b from 5 ... 15
    shuffle_slice(b, 5, 15)
    print b
    

    The code above only shuffles the elements within the specified range. The shuffle is done inplace, i.e. no copy of the list is created.

提交回复
热议问题