简体   繁体   中英

Python 2.7, how to store multiple fields into seperate list

I am opening a large text file in read mode. I was able to split the data by commas and strip it from all white space. Now I am trying to store each field into a separate list.

Example of the data:

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

Current code:

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

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

I believe my next step would be, county.append[value] but when I tried that and printed county, it printed:

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

Does anyone have any guidance on how to write each column into it's own individual list?

You're pretty close! I would iterate over all of the lines, splitting each on the comma character to create the underlying row of data. Then, append each individual component of the row to its appropriate list:

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

An arguably more pythonic way of doing this would be through list comprehensions. Say you have a .csv file named "file.csv" containing the data. The following would give you what you want:

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]

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