简体   繁体   English

如何在Python中将列数据从文本文件转换为列表?

[英]How to convert column data from text file into list in Python?

I have a text file that contains data in two columns, each of which I want to read into Python as a list. 我有一个文本文件,其中包含两列数据,我想将每一列数据读入Python列表。

For example : 例如 :

       2500.3410      -0.60960758
       2505.5803       -1.3031826
       2510.8197      -0.64067196
       2516.0593       -1.0230898
       2521.2991      -0.20078891

I want to create two lists, one containing the data from column 1 and the other column 2, but I don't know how to tell Python to do this. 我想创建两个列表,一个包含第1列中的数据,另一个包含第2列中的数据,但是我不知道如何告诉Python执行此操作。

Eg 例如

list1 = [2500.3410, 2505.5803, 2510.8197, 2516.0593, 2521.2991]      

I have opened the file in the shell and can read in the data, as above, but I'm stuck when it comes to creating the lists. 如上所述,我已经在外壳中打开了文件并且可以读取数据,但是在创建列表时遇到了麻烦。

You can use zip function and float within map : 您可以使用zip函数并在map float

zip(*[map(float,line.split()) for line in open('in_file')])

Demo: 演示:

>>> s="""       2500.3410      -0.60960758
...        2505.5803       -1.3031826
...        2510.8197      -0.64067196
...        2516.0593       -1.0230898
...        2521.2991      -0.20078891"""
>>> 
>>> [i.split() for i in s.split('\n')]
[['2500.3410', '-0.60960758'], ['2505.5803', '-1.3031826'], ['2510.8197', '-0.64067196'], ['2516.0593', '-1.0230898'], ['2521.2991', '-0.20078891']]
>>> zip(*[map(float,i.split()) for i in s.split('\n')])
[(2500.341, 2505.5803, 2510.8197, 2516.0593, 2521.2991), (-0.60960758, -1.3031826, -0.64067196, -1.0230898, -0.20078891)]

But note as zip return a list of tuples you can use map function to convert the result to list : 但是请注意,作为zip返回的元组列表,您可以使用map函数将结果转换为list:

>>> map(list,zip(*[map(float,i.split()) for i in s.split('\n')]))
[[2500.341, 2505.5803, 2510.8197, 2516.0593, 2521.2991], [-0.60960758, -1.3031826, -0.64067196, -1.0230898, -0.20078891]]

First of all you have to read the text file in Python , for an instance if you have a file named record.txt containg dataset, 首先,您必须使用Python读取文本文件,例如,如果您有一个名为record.txt包含数据集的文件,

file <- open('record.txt')

now you have to read the file line by line : 现在您必须逐行读取文件:

lst = [] 

stores the whole file as a list of list and each inner list represents an instance 将整个文件存储为列表列表,每个内部列表表示一个实例

for line in file:
    lst.append([ float(x) for x in line.split()])

now you can extract the column1 as a list and column 2 as a list by following comprehension 现在,您可以按照以下理解将column1提取为列表,将column 2提取为列表

column1 = [ x[0] for x in lst]
column2 = [ x[1] for x in lst]

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

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