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. 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])]

Answers


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:

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

Need Your Help

How to load TimelineJS development version instead of minimized storyjs-embed.js?

javascript timeline

I didn't find any clue how to load the development version of storyjs-embed.js, anyone has experience on this?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.