Break python list into multiple lists, shuffle each lists separately [duplicate]

本秂侑毒 提交于 2020-01-07 05:08:31

问题


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>]

回答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.



来源:https://stackoverflow.com/questions/39520805/break-python-list-into-multiple-lists-shuffle-each-lists-separately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!