如何按n个元素对python中的元素进行分组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4998427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to group elements in python by n elements?
提问by TheOne
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:
我想从列表 l 中获取大小为 n 个元素的组:
ie:
IE:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
回答by Adam Vandenberg
See examples at the bottom of the itertools docs: http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
请参阅 itertools 文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
You want the "grouper" method, or something like it.
您需要“石斑鱼”方法或类似方法。
回答by Mike DeSimone
Well, the brute force answer is:
好吧,蛮力答案是:
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
where Nis the group size (3 in your case):
N组大小在哪里(在您的情况下为 3):
>>> 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]]
回答by Mark Byers
回答by sizzzzlerz
How about
怎么样
a = range(1,10)
n = 3
out = [a[k:k+n] for k in range(0, len(a), n)]
回答by inspectorG4dget
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
answer = answer[:-1]

