Search code examples
pythonlistoptimization

How can I randomly select some four elements and shuffle them in list of python?


I struck on how to randomly select 4 elements and shuffle them in the first sublist while other 6 points do not move. For example,the first list should be [[1,4,3,2,5,6,10,8,9,7],[4,2,3,1,5,6,7,9,8,10],[7,3,2,4,5,6,1,8,9,10]].

import random

Bestsmell=([[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]],[[6,7,8,9,10,11,12,13,14,15],[6,7,8,9,10,11,12,13,14,15],[6,7,8,9,10,11,12,13,14,15]])
for i in range (3):
    x = Bestsmell[0][i]
    random.shuffle(x) 

Thanks for your reccomendation.


Solution

    • Pick 4 random indexes of the list.
    • Make a list of the values at those indexes.
    • Shuffle the list of values (or the list of indexes)
    • Assign these values back to those indexes in the original list.
    import random
    
    def shuffle_4(l):
        indexes = random.sample(range(len(l)), k=4)
        values = [l[i] for i in indexes]
        random.shuffle(values)
        for i, val in zip(indexes, values):
            l[i] = val
    
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    shuffle_4(nums)
    print(nums)