Let's say I have posts in ordered list according to their date.
[, , , , , ]
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:
[[, ], [, ], [, ]]
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:
[[, ], [, ], [, ]]
or better:
[, , , , , ]
解决方案
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,itertools
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
print(sum(chunks,[])) # or (more complex but faster below)
print(list(itertools.chain(*chunks))) # faster than sum on big lists
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 [[, , , , , ]] (list in a list) but I suppose that's a typo: I provide a simple, flattened list.