Python 将函数映射到列表迭代器的列
假设我在一个csv文件中读取的数字如下所示:Python 将函数映射到列表迭代器的列,python,csv,iterator,Python,Csv,Iterator,假设我在一个csv文件中读取的数字如下所示: 1,6.2,10 5.4,5,11 17,1.5,5 ... import csv reader = csv.reader('numbers.csv') def max(iterator): themax = float('-inf') for i in iterator: themax = i if i > themax else themax yield yield themax
1,6.2,10
5.4,5,11
17,1.5,5
...
import csv
reader = csv.reader('numbers.csv')
def max(iterator):
themax = float('-inf')
for i in iterator:
themax = i if i > themax else themax
yield
yield themax
而且真的很长
我将使用如下csv阅读器遍历此文件:
1,6.2,10
5.4,5,11
17,1.5,5
...
import csv
reader = csv.reader('numbers.csv')
def max(iterator):
themax = float('-inf')
for i in iterator:
themax = i if i > themax else themax
yield
yield themax
现在假设我有一个函数,可以使用像max这样的迭代器:
max((float(rec[0]) for rec in reader))
这会找到第一列的最大值,不需要将整个文件读入内存
但是,如果我想在csv文件的每一列上运行max,而不将整个文件读入内存,该怎么办
如果max被改写成这样:
1,6.2,10
5.4,5,11
17,1.5,5
...
import csv
reader = csv.reader('numbers.csv')
def max(iterator):
themax = float('-inf')
for i in iterator:
themax = i if i > themax else themax
yield
yield themax
然后我可以做一些花哨的工作(而且必须)来实现这一点
但是,如果我限制了问题,不允许重写max,该怎么办?这可能吗
谢谢 我不再使用传递迭代器的函数,而是自己在读卡器上迭代:
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
,而不必将整个文件存储在内存中。如果您对更实用的方法感到满意,可以使用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)]
现在functools.reduce(col_max、reader、initializer)将返回您想要的结果。您必须提供初始值设定项作为正确长度的-inf列表