Break Python List Into Multiple Lists, Shuffle Each Lists Separately
Let's say I have posts in ordered list according to their date. [, , , , , ] I want to br
Solution 1:
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 [[<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.
Post a Comment for "Break Python List Into Multiple Lists, Shuffle Each Lists Separately"