在 Python 中分割列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1218793/
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
Segment a list in Python
提问by kjfletch
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
我正在寻找一个 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]]
回答by OmerGertel
You can use list comprehension:
您可以使用列表理解:
>>> 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]]
回答by Martijn Pieters
How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:
你需要如何使用输出?如果你只需要迭代它,你最好创建一个可迭代的,一个产生你的组:
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
Usage example:
用法示例:
>>> alist = range(10)
>>> list(split_by(alist, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:
这比尝试一次在内存中构建整个列表使用的内存要少得多,如果您只循环访问结果,因为它一次只构建一个子集:
>>> for subset in split_by(alist, 3):
... print subset
...
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
回答by sunqiang
not the same output, I still think the grouper functionis helpful:
不一样的输出,我仍然认为grouper 功能是有帮助的:
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
for Python2.4 and 2.5 that does not have izip_longest:
对于没有 izip_longest 的 Python2.4 和 2.5:
from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
some demo code and output:
一些演示代码和输出:
alist = range(10)
print list(grouper(alist, 3))
output: [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
输出:[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]