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\'
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']
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:
create a new list of only the elements you want to shuffle.
shuffle the new list.
remove those elements you wanted to shuffle from your original list.
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)