[英]Loading data from a csv file and display in list of tuples
Does anyone have an idea on how to write a function loading_values(csvfilename)
that takes a string corresponding to the name of the data file and returns a list of tuples containing the subset name (as a string) and a list of floating point data values. 有没有人知道如何编写一个函数
loading_values(csvfilename)
,它接受一个对应于数据文件名称的字符串,并返回一个包含子集名称(作为字符串)和浮点数据值列表的元组列表。 the result should be something like this when the function is called 调用函数时,结果应该是这样的
>>> 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])]
for now my code returns separate tuples for each subheading not joined by (,) 现在我的代码为每个没有加入的子标题返回单独的元组(,)
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])]
Try: 尝试:
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`)
or you may use csv module : 或者您可以使用csv模块 :
import csv
with open('statistics.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
results = map( lambda x: (x[0],x[1:]), reader)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.