Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading