简体   繁体   中英

Extract data from list in python

I am using a program that spits result in format [(11,3.22),(12,4.6),(9,2.4)] I need to extract the first part to change it to names and attach the second value and store this in a csv file. How do I extract each part of subpart?

>>> l = [(11,3.22),(12,4.6),(9,2.4)]

"need to extract the first part" -

>>> l[0]
(11, 3.22)

"change it to names" -

>>> l[0] = ('x', 'y')
>>> l
[('x', 'y'), (12, 4.6), (9, 2.4)]

"attach the second value" -

>>> l[0] = dict(zip(('x', 'y'), l[1]))
>>> l
[{'y': 4.6, 'x': 12}, (12, 4.6), (9, 2.4)]

Storing in CSV is easy, check an example here - http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/

I am assuming that you mean for each tuple in the list, replace the first element with a string that's mapped from the integer.

You can use list comprehensions to do so:

>>> id_to_str_map = {11:"foo", 12:"bar", 9:"baz"}
>>> l = [(11,3.22),(12,4.6),(9,2.4)]
>>> result = [(id_to_str_map[idx], value) for (idx, value) in l]
>>> print result
[('foo', 3.22), ('bar', 4.6), ('baz', 2.4)]

Using the CSV standard library module as recommended by @theharshest is the most robust option. Standard library documentation for Python 2.7: http://docs.python.org/2/library/csv.html

If you're working with a large dataset, then it's likely better to instead use a generator expression to lazily perform the mapping as you are writing out each row to the csv file.

import csv
id_to_str_map = {11:"foo", 12:"bar", 9:"baz"}
l = [(11,3.22),(12,4.6),(9,2.4)]
with open("blah.csv", "wb") as csvfile:
    csv_writer = csv.writer(csvfile)
    for row in ((d[idx], value) for (idx, value) in l):
        csv_writer.writerow(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM