Henry H Henry H - 1 year ago 68
Python Question

Break python list into multiple lists, shuffle each lists separately

Let's say I have posts in ordered list according to their date.

[<Post: 6>, <Post: 5>, <Post: 4>, <Post: 3>, <Post: 2>, <Post: 1>]

I want to break them into 3 groups, and shuffle the items inside the list accordingly.

chunks = [posts[x:x+2] for x in xrange(0, len(posts), 2)]

Now Chunks will return:

[[<Post: 6>, <Post: 5>], [<Post: 4>, <Post: 3>], [<Post: 2>, <Post: 1>]]

What are some efficient ways to randomly shuffle these items inside each respective lists?
I could think of iterating through them, creating each respective lists but this seems repetitive...

I want the final output to look something like:

[[<Post: 5>, <Post: 6>], [<Post: 4>, <Post: 3>], [<Post: 1>, <Post: 2>]]

or better:

[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <Post: 1>, <Post: 2>]

Answer Source

Sure. random.shuffle works in-place so looping through list elements and applying it on them does the first job. For the "flattening" I use a favorite trick of mine: applying sum on sublists with start element as empty list.

import random

chunks = [["Post: 6", "Post: 5"], ["Post: 4", "Post: 3"], ["Post: 2", "Post: 1"]]

# shuffle

for c in chunks: random.shuffle(c)

# there you already have your list of lists with shuffled sub-lists
# now the flattening


Some results:

['Post: 5', 'Post: 6', 'Post: 4', 'Post: 3', 'Post: 2', 'Post: 1']
['Post: 6', 'Post: 5', 'Post: 3', 'Post: 4', 'Post: 1', 'Post: 2']

(you said you wanted something like [[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <Post: 1>, <Post: 2>]] (list in a list) but I suppose that's a typo: I provide a simple, flattened list.