我正在寻找一个python内置函数(或机制)来将列表分段为所需的段长度(不改变输入列表)。这是我已有的代码:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
答案 0 :(得分:18)
您可以使用列表理解:
>>> seg_length = 3
>>> a = range(10)
>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
答案 1 :(得分:5)
您如何使用输出?如果你只需要迭代它,你最好创建一个可以产生你的组的迭代:
def split_by(sequence, length):
iterable = iter(sequence)
def yield_length():
for i in xrange(length):
yield iterable.next()
while True:
res = list(yield_length())
if not res:
return
yield res
用法示例:
>>> alist = range(10)
>>> list(split_by(alist, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
如果你只是在结果上循环,那么使用的内存比尝试在内存中同时构建整个列表要少得多,因为它一次只构造一个子集:
>>> for subset in split_by(alist, 3):
... print subset
...
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
答案 2 :(得分:2)
输出不一样,我仍然认为grouper function很有用:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
对于Python2.4和2.5没有izip_longest:
from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
一些演示代码和输出:
alist = range(10)
print list(grouper(alist, 3))
输出: [(0,1,2),(3,4,5),(6,7,8),(9,无,无)]