Skip to content

Latest commit

 

History

History
52 lines (34 loc) · 1.93 KB

113.md

File metadata and controls

52 lines (34 loc) · 1.93 KB

#如何将Python列表均匀划分?

原问题地址:http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python

##问题:

我有一个任意长度的列表,我需要把它拆分成长度相等的更小的数据集,然后进行操作。有一些平淡无奇的方法可以实现这一需求,比如:保存一个计数器和两个列表,当第二个列表填满时,将第二个列表添加到第一个列表,然后清空第二个列表以便填充下一轮数据,但这样做的代价可能是非常昂贵的。

我想知道是否有人想出了一个很好的解决方案,使之适用于于任何长度的列表,例如;使用生成器。

这个方案应该能够奏效:

l = range(1, 1000)
print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ]

我曾经在itertools中寻找一些有用的东西,但我找不到任何明显有用的东西。然而,我可能错过了它。

##回答:

这是一个生成器,它可以生成你想要的数据集:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i+n]

import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]

如果你正在使用Python 2,你应该使用xrange()来代替range()

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

你也可以简单地使用列表解析来代替函数的书写。

Python 3:

[l[i:i+n] for i in range(0, len(l), n)]

Python2:

[l[i:i+n] for i in xrange(0, len(l), n)]