如何在恒定大小的块中拆分可迭代 [英] how to split an iterable in constant-size chunks

查看:162
本文介绍了如何在恒定大小的块中拆分可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


$ b如何在Python中将列表拆分成均匀大小的块?


我很惊讶我找不到一个批处理函数,它将输入一个可迭代的值并返回一个可迭代的迭代器。



例如:

 对于i在批处理中(范围(0,10),1):打印我
[0]
[1]
...
[9]

或:

  for i in batch(range(0,10),3):打印我
[0,1,2]
[3,4,5]
[6,7,8]
[9]

现在,我写了我认为很简单的生成器:

  def批处理(可迭代,n = 1):
current_batch = []
可迭代项:
current_batch.append(item)
如果len(current_batch)== n:
yield current_batch
current_batch = []
如果current_batch:
yield current_batch

但是以上内容并没有给我我所期望的:

 对于x批量(范围(0,10) ,3):打印x 
[0]
[0,1]
[0,1,2]
[3]
[3,4]
[3,4,5]
[6]
[6,7]
[6,7,8]
[9]

因此,我错过了一些东西,这可能表明我完全不了解python生成器。任何人都想指出正确的方向吗?



/ p>

解决方案

这可能更有效(更快)

  def批处理(iterable,n = 1):
l = len(可迭代)
对于ndx范围(0,l,n):
产生iterable [ndx: min(ndx + n,l)]

for x in batch(range(0,10),3):
print x






使用列表示例

  data = [0,1,2,3,4,5,6,7,8,9,10]#数据列表

批量x(数据,3):
打印(x)

#输出

[0,1,2]
[3,4 ,5]
[6,7,8]
[9,10]

它避免建立新列表。


Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

I am surprised I could not find a "batch" function that would take as input an iterable and return an iterable of iterables.

For example:

for i in batch(range(0,10), 1): print i
[0]
[1]
...
[9]

or:

for i in batch(range(0,10), 3): print i
[0,1,2]
[3,4,5]
[6,7,8]
[9]

Now, I wrote what I thought was a pretty simple generator:

def batch(iterable, n = 1):
   current_batch = []
   for item in iterable:
       current_batch.append(item)
       if len(current_batch) == n:
           yield current_batch
           current_batch = []
   if current_batch:
       yield current_batch

But the above does not give me what I would have expected:

for x in   batch(range(0,10),3): print x
[0]
[0, 1]
[0, 1, 2]
[3]
[3, 4]
[3, 4, 5]
[6]
[6, 7]
[6, 7, 8]
[9]

So, I have missed something and this probably shows my complete lack of understanding of python generators. Anyone would care to point me in the right direction ?

[Edit: I eventually realized that the above behavior happens only when I run this within ipython rather than python itself]

解决方案

This is probably more efficient (faster)

def batch(iterable, n=1):
    l = len(iterable)
    for ndx in range(0, l, n):
        yield iterable[ndx:min(ndx + n, l)]

for x in batch(range(0, 10), 3):
    print x


Example using list

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # list of data 

for x in batch(data, 3):
    print(x)

# Output

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10]

It avoids building new lists.

这篇关于如何在恒定大小的块中拆分可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆