How to shuffle list items keeping the similar items unshuffled? E.g. for the list 'L', I want to shuffle among the unique items.
L=[a,a,b,b,c,c,d,d]
For the above list, I want to get
shuffled_L=[c,c,a,a,d,d,b,b]
Group into tuples, shuffle the tuples, flatten the list again:
>>> from itertools import groupby, chain
>>> from random import shuffle
>>> L = ["a", "a", "b", "b", "c", "c", "d", "d"]
>>> L_ = [tuple(v) for _, v in groupby(L)]
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]
>>> random.shuffle(L_)
[('b', 'b'), ('a', 'a'), ('d', 'd'), ('c', 'c')]
>>> list(chain.from_iterable(L_))
['b', 'b', 'a', 'a', 'd', 'd', 'c', 'c']
This assumes the original L
is already sorted. If it isn't, sort
it before the groupby
step.