从csv文件加载数据并显示在元组列表中

时间:2015-08-19 11:54:11

标签: python list function csv tuples

有没有人知道如何编写一个函数loading_values(csvfilename),它接受​​一个与数据文件名相对应的字符串,并返回一个包含子集名称(作为字符串)和列表的元组列表浮点数据值。 当调用函数时,结果应该是这样的

>>> stat = loading_values(`statistics.csv`)
>>> stat
     [('Pressure', [31.52, 20.3, ..., 27.90, 59.58]),
      ('Temp', [97.81, 57.99, ..., 57.80, 64.64]),
      ('Range', [79.10, 42.83, ..., 68.84, 26.88])]

现在我的代码为每个没有由(,)

连接的子标题返回单独的元组
f=open('statistics.csv', 'r')
for c in f:
    numbers = c.split(',')
    numbers = (numbers[0], (numbers[1::]))

[('Pressure', [31.52, 20.3, ..., 27.90, 59.58])
 ('Temp', [97.81, 57.99, ..., 57.80, 64.64])
 ('Range', [79.10, 42.83, ..., 68.84, 26.88])]

1 个答案:

答案 0 :(得分:4)

尝试:

def loading_values(csvfile):
    f=open(csvfile, 'r')
    results = []
    for line in f:
        numbers = list(map(lambda x: x.strip(), line.split(',')))
        results.append((numbers[0], numbers[1:]))

    return results

print loading_values(`statistics.csv`)

或者您可以使用csv module

import csv
with open('statistics.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    results = map( lambda x: (x[0],x[1:]), reader)