想象一下,我正在读取一个csv文件中的数字,如下所示:
1,6.2,10
5.4,5,11
17,1.5,5
...
而且它真的很长。
我将使用csv阅读器遍历此文件,如下所示:
import csv
reader = csv.reader('numbers.csv')
现在假设我有一些函数可以接受像max这样的迭代器:
max((float(rec[0]) for rec in reader))
这会找到第一列的最大值,而不需要将整个文件读取到内存中。
但是,如果我想对csv文件的每一列运行max,而不将整个文件读取到内存中,该怎么办?
如果max像这样重写:
def max(iterator):
themax = float('-inf')
for i in iterator:
themax = i if i > themax else themax
yield
yield themax
然后,我可以做一些花哨的工作(并且必须)来实现这一点。
但是如果我约束问题并且不允许重写max呢?这个是可能的吗?
谢谢!
发布于 2014-01-28 09:29:00
如果您习惯于使用更实用的方法,可以使用functools.reduce遍历文件,一次只将两行放入内存,并在执行过程中累加列的最大值。
import csv
from functools import reduce
def column_max(row1, row2):
# zip contiguous rows and apply max to each of the column pairs
return [max(float(c1), float(c2)) for (c1, c2) in zip(row1, row2)]
reader = csv.reader('numbers.csv')
# calling `next` on reader advances its state by one row
first_row = next(reader)
column_maxes = reduce(column_max, reader, first_row)
#
#
# another way to write this code is to unpack the reduction into explicit iteration
column_maxes = next(reader) # advances `reader` to its second row
for row in reader:
column_maxes = [max(float(c1), float(c2)) for (c1, c2) in zip(column_maxes, row)]
发布于 2014-01-28 08:03:05
我将不再使用传递迭代器的函数,而是自己在阅读器上迭代:
maxes = []
for row in reader:
for i in range(len(row)):
if i > len(maxes):
maxes.append(row[i])
else:
maxes[i] = max(maxes[i], row[i])
最后,您将获得包含每个最大值的列表maxes
,而无需在内存中存储整个文件。
发布于 2014-01-28 10:59:26
def col_max(x0,x1):
"""x0 is a list of the accumulated maxes so far,
x1 is a line from the file."""
return [max(a,b) for a,b in zip(x0,x1)]
现在functools.reduce(col_max,reader,initializer)将返回您想要的内容。您必须以正确长度的-inf列表的形式提供初始化器。
https://stackoverflow.com/questions/21394296
复制相似问题