Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle groups of sublists in Python

Tags:

python

I want to shuffle this list:

[[1, 'A'], [2, 'A'], [6, 'B'], [3, 'B'], [4, 'C'], [5, 'C'], [7, 'F']]

But I need groups identified by sublists second elements to stay together, so that the shuffled list could look like this:

[[6, 'B'], [3, 'B'], [7, 'F'], [1, 'A'], [2, 'A'], [4, 'C'], [5, 'C']]

Where all 'B', 'F', 'A', and 'C' sublists stay together.

I'm guessing using a combination of shuffle and groupby would do the trick, but I don't know where to start with this. Any idea would be appreciated!

like image 340
Lucien S. Avatar asked Feb 07 '26 16:02

Lucien S.


1 Answers

items = [[1, 'A'], [2, 'A'], [6, 'B'], [3, 'B'], [4, 'C'], [5, 'C'], [7, 'F']]

import itertools, operator, random

groups = [list(g) for _, g in itertools.groupby(items, operator.itemgetter(1))]
random.shuffle(groups)
shuffled = [item for group in groups for item in group]

print(shuffled)

Prints for example:

[[4, 'C'], [5, 'C'], [1, 'A'], [2, 'A'], [7, 'F'], [6, 'B'], [3, 'B']]
like image 93
Stefan Pochmann Avatar answered Feb 09 '26 04:02

Stefan Pochmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!