Python 将多个函数映射到CSV行

Python 将多个函数映射到CSV行,python,Python,我正在尝试对完全由字符串组成的CSV数据进行一些类型转换。我想我应该使用一个函数头名称字典,并将这些函数映射到每个CSV行。我只是有点被困在如何有效地将多个函数映射到一行上。我正在考虑枚举头并创建一个新的函数索引字典: header_map = {'Foo':str, 'Bar':str, 'FooBar':float} csv_data = [('Foo', 'Bar', 'FooBar'), #lots of

我正在尝试对完全由字符串组成的CSV数据进行一些类型转换。我想我应该使用一个函数头名称字典,并将这些函数映射到每个CSV行。我只是有点被困在如何有效地将多个函数映射到一行上。我正在考虑枚举头并创建一个新的函数索引字典:

header_map = {'Foo':str,
              'Bar':str,
              'FooBar':float}

csv_data = [('Foo', 'Bar', 'FooBar'),
            #lots of data...
           ]

index_map = {}

#enumerate the rows and create a dictionary of index:function
for i, header in enumerate(csv_data[0]):
    index_map[i] = header_map[header]

#retrieve the function for each index and call it on the value
new_csv = [[index_map[i](value) for i, value in enumerate(row)] 
           for row in csv_data[1:]]
我只是好奇,是否有人知道更简单、有效的方法来完成这种类型的操作

没有测试(没有样本输入),但这似乎满足了您的要求:

heads = csv_data[0]
new_csv = heads + [
              tuple(header_map[head](item) for head, item in zip(heads, row))
          for row in csv_data[1:]]

如果您知道标题在标题中的顺序,您可以使用函数列表而不是dict

>>> header = [str, str, float]
>>> csv = [("aaa", "bbb", "3.14")] * 10
>>> map(lambda line: map(lambda f, arg: f(arg), header, line), csv)
[['aaa', 'bbb', 3.14], ['aaa', 'bbb', 3.14], ...

这里有一种方法,
使用_converter
,速度稍快:

import itertools as IT

header_map = {'Foo':str,
              'Bar':str,
              'FooBar':float}

N = 20000
csv_data = [('Foo', 'Bar', 'FooBar')] + [('Foo', 'Bar', 1123.451)]*N

def original(csv_data):
    index_map = {}
    #enumerate the rows and create a dictionary of index:function
    for i, header in enumerate(csv_data[0]):
        index_map[i] = header_map[header]

    #retrieve the appropriate function for each index and call it on the value
    new_csv = [[index_map[i](value) for i, value in enumerate(row)]
               for row in csv_data[1:]]
    return new_csv

def using_converter(csv_data):
    converters = IT.cycle([header_map[header] for header in csv_data[0]])
    conv = converters.next
    new_csv = [[conv()(item) for item in row] for row in csv_data[1:]]
    return new_csv

def using_header_map(csv_data):
    heads = csv_data[0]
    new_csv = [
        tuple(header_map[head](item) for head, item in zip(heads, row))
        for row in csv_data[1:]]
    return new_csv

# print(original(csv_data))
# print(using_converter(csv_data))
# print(using_header_map(csv_data))

使用
timeit
进行基准测试:

原代码:

% python -mtimeit -s'import test' 'test.original(test.csv_data)'
100 loops, best of 3: 17.3 msec per loop
稍微快一点的版本(使用itertools):

Lev Levitsky的版本:

% python -mtimeit -s'import test' 'test.using_header_map(test.csv_data)'
10 loops, best of 3: 36.2 msec per loop
% python -mtimeit -s'import test' 'test.using_header_map(test.csv_data)'
10 loops, best of 3: 36.2 msec per loop