可能重复:
如何在Python中将列表拆分为大小均匀的块?
我很惊讶我找不到一个"批处理"函数,它将输入迭代并返回一个可迭代的迭代.
例如:
for i in batch(range(0,10), 1): print i
[0]
[1]
...
[9]
Run Code Online (Sandbox Code Playgroud)
要么:
for i in batch(range(0,10), 3): print i
[0,1,2]
[3,4,5]
[6,7,8]
[9]
Run Code Online (Sandbox Code Playgroud)
现在,我写了一个我认为非常简单的生成器:
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
Run Code Online (Sandbox Code Playgroud)
但上面没有给我我所期望的:
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] …Run Code Online (Sandbox Code Playgroud) 根据我们客户的要求,我必须开发一个应该能够处理大量CSV文件的应用程序.文件大小可以在10 MB - 2GB的范围内.
根据大小,模块决定是Multiprocessing pool使用普通文件还是使用普通文件来读取文件CSV reader.但是从观察开始,在测试大小为100 MB的文件的两种模式时,multi processing需要比平时更长的时间CSV reading.
这是正确的行为吗?或者我做错了什么?
这是我的代码:
def set_file_processing_mode(self, fpath):
""" """
fsize = self.get_file_size(fpath)
if fsize > FILE_SIZE_200MB:
self.read_in_async_mode = True
else:
self.read_in_async_mode = False
def read_line_by_line(self, filepath):
"""Reads CSV line by line"""
with open(filepath, 'rb') as csvin:
csvin = csv.reader(csvin, delimiter=',')
for row in iter(csvin):
yield row
def read_huge_file(self, filepath):
"""Read file in chunks"""
pool = mp.Pool(1)
for chunk_number in range(self.chunks): #self.chunks = 20
proc …Run Code Online (Sandbox Code Playgroud)