用于列出TypeError的Python csv:无法使用灵活类型执行reduce

时间:2014-11-29 19:27:41

标签: python

我正在尝试获取看起来像这样的test.csv文件:
小时,MIME,活性
100,0.41,1
101,0.19,1
102,0.18,1
103,0.6,1
104,0.45,1
105,0.7,1
90,0.4,1
72.43,0.17,1
73,0.17,1
110,0.5,1
120,1,1
130,2,1
72.19,0.5,1
72.68,0.5,1

看起来像这样:

data = ((100, 0.4, 1), (101, 0.19, 1), (102, 0.18, 1), (103, 0.4, 1),
        (104, 0.4, 1), (105, 0.4, 1), (90, 0.4, 1), (72.43, 0.17, 1),
        (73, 0.17, 1), (110, 0.5, 1), (120, 0.17, 1), (130, 0.18, 1),
        (72.19, 0.5, 1), (72.68, 0.5, 1))

我尝试过以下方法:

import csv
with open('test.csv', 'rb') as f:
    reader = csv.reader(f)
    data = map(tuple, reader)

但是当它被打印时它看起来像这样:

[('hr', 'mime', 'active'), ('100', '0.41', '1'), ('101', '0.19', '1'), ('102', '0.18', '1'), ('103', '0.6', '1'), ('104', '0.45', '1'), ('105', '0.7', '1'), ('90', '0.4', '1'), ('72.43', '0.17', '1'), ('73', '0.17', '1'), ('110', '0.5', '1'), ('120', '1', '1'), ('130', '2', '1'), ('72.19', '0.5', '1'), ('72.68', '0.5', '1')]

此外,当我尝试使用hr运行某些代码时,我收到此错误:

TypeError: cannot perform reduce with flexible type

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这应该有效:

import csv

def convert(line):
    return tuple(map(float, line))

with open('test.csv', 'rb') as f:
    reader = tuple(csv.reader(f))[1:]
    data = tuple(map(convert, reader))