How to group elements in python by n elements?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
我想从列表L中获取一组大小为n的元素:
IE:
1 | [1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3 |
您可以从ITertools文档页面的食谱中使用Grouper:
1 2 3 4 | def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) |
嗯,暴力的答案是:
1 | subList = [theList[n:n+N] for n in range(0, len(theList), N)] |
其中,
1 2 3 4 5 | >>> 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]] |
如果需要填充值,可以在列表理解之前执行此操作:
1 2 | tempList = theList + [fill] * N subList = [tempList[n:n+N] for n in range(0, len(theList), N)] |
例子:
1 2 3 4 5 | >>> 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]] |
请参阅itertools文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools模块itertools
你想要"Grouper"方法,或者类似的方法。
怎么样
1 2 3 | a = range(1,10) n = 3 out = [a[k::k+n] for k in range(0,len(a),n)] |
1 2 3 | answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)] if not answer[-1]: answer = answer[:-1] |