如何按n个元素对python中的元素进行分组 [英] How to group elements in python by n elements
本文介绍了如何按n个元素对python中的元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何将列表平均拆分Python 中的大小块?
我想从列表 l 中获取大小为 n 个元素的组:
即:
[1,2,3,4,5,6,7,8,9] ->[[1,2,3], [4,5,6],[7,8,9]] 其中 n 为 3
解决方案
好吧,蛮力的答案是:
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
其中 N
是组大小(在您的情况下为 3):
如果你想要一个填充值,你可以在列表理解之前这样做:
tempList = theList + [fill] * NsubList = [tempList[n:n+N] for n in range(0, len(theList), N)]
示例:
<预><代码>>>>填充 = 99>>>tempList = theList + [fill] * N>>>subList = [tempList[n:n+N] for n in range(0, len(theList), N)]>>>子列表[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I'd like to get groups of size n elements from a list l:
ie:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
解决方案
Well, the brute force answer is:
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
where N
is the group size (3 in your case):
>>> theList = list(range(10))
>>> N = 3
>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
If you want a fill value, you can do this right before the list comprehension:
tempList = theList + [fill] * N
subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
Example:
>>> fill = 99
>>> tempList = theList + [fill] * N
>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]
这篇关于如何按n个元素对python中的元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文