Python - shuffle only some elements of a list

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

    You can create your own shuffle function that will allow you to shuffle a slice within a mutable sequence. It handles sampling the slice copy and reassigning back to the slice. You must pass slice() arguments instead of the more familiar [2:] notation.

    from random import sample
    def myShuffle(x, *s):
        x[slice(*s)] = sample(x[slice(*s)], len(x[slice(*s)]))
    

    usage:

    >>> lst = ['a?','b','c','d','e']   #don't use list as a name
    >>> myShuffle(lst, 2)              #shuffles lst[:2]
    >>> lst
    ['b', 'a?', 'c', 'd', 'e']
    >>> myShuffle(lst, 2, None)        #shuffles lst[2:]
    >>> lst
    ['b', 'a?', 'd', 'e', 'c']
    
    0 讨论(0)
  • 2020-12-06 17:57

    Try this ..it's much simpler and does not make any copies of the list.
    You can keep any of the elements fixed by just playing with the list indices.

    working:

    1. create a new list of only the elements you want to shuffle.

    2. shuffle the new list.

    3. remove those elements you wanted to shuffle from your original list.

    4. insert the newly created list into the old list at the proper index

        import random
        list = ['a?', 'b', 'c', 'd', 'e']
    
        v = []
        p = [v.append(list[c]) for c in range(2,len(list))] #step 1
        random.shuffle(v)  #step 2
        for c in range(2,len(list)):
            list.remove(list[c])  #step 3
            list.insert(c,v[c-2]) #step 4    #c-2 since the part to be shuffled begins from this index of list
    
        print(list)
    
    0 讨论(0)
提交回复
热议问题