将python列表分解成多个列表,分别随机排列每个列表 [英] 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>]
我想将它们分为3组,并相应地调整列表中的项目.
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)]
现在,块将返回:
[[<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>]]
或更好:
[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <Post: 1>, <Post: 2>]
推荐答案
好的. random.shuffle
是就地工作的,因此循环遍历列表元素并将其应用于它们就可以完成第一项工作.
对于展平",我使用了我最喜欢的技巧:在开始元素为空列表的子列表上应用sum
.
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
一些结果:
['Post: 5', 'Post: 6', 'Post: 4', 'Post: 3', 'Post: 2', 'Post: 1']
['Post: 6', 'Post: 5', 'Post: 3', 'Post: 4', 'Post: 1', 'Post: 2']
(您说过您想要类似[[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <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.
这篇关于将python列表分解成多个列表,分别随机排列每个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!