Python 2.7,如何将多个字段存储到单独的列表中

时间:2015-06-23 03:10:09

标签: python python-2.7 python-3.x

我在读取模式下打开一个大文本文件。我能够用逗号分割数据并将其从所有空格中删除。现在我试图将每个字段存储到一个单独的列表中。

数据示例:

Montgomery,2327375.079,1273061.532,3 ,3 
Stanly,2224024.174,1267300.181,5 ,5 
Henderson,1559580.515,1277200.634,5 ,5 

当前代码:

county = []
x_coor = []
y_coor = []
observed = []
expected = []

for line in lines:
        for value in line.split(','):
            value = value.strip()

我相信我的下一步将是,county.append[value]但是当我尝试并打印县时,它打印出来了:

[['3']] [['3'], ['5']] [['3'], ['5'], ['5']]

是否有人对如何将每列写入其自己的个人列表有任何指导?

2 个答案:

答案 0 :(得分:3)

你非常接近!我将迭代所有行,在逗号字符上拆分每个行以创建基础数据行。然后,将该行的每个单独组件附加到其相应的列表中:

county = []
x_coor = []
y_coor = []
observed = []
expected = []

for line in lines:
    row = line.split(',')

    county.append(row[0])
    x_coor.append(row[1])
    y_coor.append(row[2])
    observed.append(row[3])
    expected.append(row[4])

答案 1 :(得分:1)

一种可以说是更加pythonic的方式是通过列表理解。假设您有一个名为“file.csv”的.csv文件,其中包含数据。以下内容将为您提供所需内容:

import csv
with open('file.csv', 'rb') as data:
    reader = csv.reader(data)
    awesome_list = list(reader)

county = [x[0] for x in awesome_list]
x_coor = [x[1] for x in awesome_list]
y_coor = [x[2] for x in awesome_list]
observed = [x[3] for x in awesome_list]
expected = [x[4] for x in awesome_list]