Python: how to randomly shuffle a list in which each variable ends up in a new place

I would like to randomly shuffle the list so that each variable in the list falls into a new place in the list when shuffling.

What am I doing now:

list = ['a', 'b','c', 'd']; random.shuffle(list) list ['c','b','d','a'] 

With this method, I shuffle the list, but in this case it is still possible for the variable to be in the same place in this case.

My desired result

fully shuffled list

 ['c','a','d','b'] 

I appreciate any help. I am new to python, but please let me know if any further information is needed.

+6
source share
1 answer

Something like this should do what you want:

 import random import copy def super_shuffle(lst): new_lst = copy.copy(lst) random.shuffle(new_lst) for old, new in zip(lst, new_lst): if old == new: return super_shuffle(lst) return new_lst 

Example:

 In [16]: super_shuffle(['a', 'b', 'c']) Out[16]: ['b', 'c', 'a'] 
+4
source

Source: https://habr.com/ru/post/1012964/


All Articles