简体   繁体   English

从python列表中提取数据

[英]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. 我正在使用一个以[[11,3.22),(12,4.6),(9,2.4)]格式显示结果的程序,我需要提取第一部分以将其更改为名称,然后附加第二个值并将其存储在CSV文件。 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/ 以CSV格式存储很容易,请在此处查看示例-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. 使用@theharshest建议的CSV标准库模块是最可靠的选择。 Standard library documentation for Python 2.7: http://docs.python.org/2/library/csv.html 适用于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. 如果您正在使用大型数据集,那么最好在将每一行写到csv文件中时,使用生成器表达式来懒惰地执行映射。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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