将列表分成 n 组的另一种方法 [英] Alternative way to split a list into groups of n
问题描述
假设我有一个任意长度的列表,L:
L = list(range(1000))
将该列表分成 n
组的最佳方法是什么?这是我能想出的最好的结构,但出于某种原因,这并不是完成任务的最佳方式:
n = 25对于范围内的 i (0, len(L), n):块 = L[i:i+25]
是否有内置工具可以执行此操作?
早期的答案是将我的 for 循环改造成 listcomp,这不是想法;你基本上是在以不同的形式给我我的确切答案.我正在查看是否有替代方法来完成此操作,例如列表中的假设 .split
或其他内容.我也在昨晚写的一些代码中使用它作为生成器:
def split_list(L, n):assert type(L) 是列表,L 不是列表"对于范围内的 i (0, len(L), n):产量 L[i:i+n]
A Python配方(在 Python 2.6 中,使用 itertools.izip_longest
):
def grouper(n, iterable, fillvalue=None):石斑鱼(3,'ABCDEFG','x')--> ABC DEF Gxx"args = [iter(iterable)] * nreturn itertools.zip_longest(*args, fillvalue=fillvalue)
示例用法:
<预><代码>>>>列表(石斑鱼(3,范围(9)))[(0, 1, 2), (3, 4, 5), (6, 7, 8)]>>>列表(石斑鱼(3,范围(10)))[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]如果您希望最后一组比其他组短而不是用 fillvalue
填充,那么您可以例如像这样更改代码:
Let's say I have a list of arbitrary length, L:
L = list(range(1000))
What is the best way to split that list into groups of n
? This is the best structure that I have been able to come up with, and for some reason it does not feel like it is the best way of accomplishing the task:
n = 25
for i in range(0, len(L), n):
chunk = L[i:i+25]
Is there a built-in to do this I'm missing?
Edit: Early answers are reworking my for loop into a listcomp, which is not the idea; you're basically giving me my exact answer back in a different form. I'm seeing if there's an alternate means to accomplish this, like a hypothetical .split
on lists or something. I also do use this as a generator in some code that I wrote last night:
def split_list(L, n):
assert type(L) is list, "L is not a list"
for i in range(0, len(L), n):
yield L[i:i+n]
A Python recipe (In Python 2.6, use itertools.izip_longest
):
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
Example usage:
>>> list(grouper(3, range(9)))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(grouper(3, range(10)))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
If you want the last group to be shorter than the others instead of padded with fillvalue
, then you could e.g. change the code like this:
>>> def mygrouper(n, iterable):
... args = [iter(iterable)] * n
... return ([e for e in t if e != None] for t in itertools.zip_longest(*args))
...
>>> list(mygrouper(3, range(9)))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> list(mygrouper(3, range(10)))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
这篇关于将列表分成 n 组的另一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!