Loading data from a csv file and displaying tuples in a list

Does anyone know how to write a loading_values(csvfilename) function that takes a string corresponding to the name of a data file and returns a list of tuples containing the name of the subset (as a string) and a floating point list of the data value. 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])] 

now my code returns separate tuples for each subtitle unrelated to (,)

 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])] 
+5
source share
1 answer

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 can use the 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) 
+4
source

All Articles