Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

python - Read columns into separate lists

I have a text file with more than 10 lines and 3 columns like:

Classification Type  A  B
Commercial Homes     12 15
Residential Homes    10 14
................     .. ..

I want to read each column separately like:

Classification = ['Commercial Homes', 'Residential Homes'.......]
A = [12,10,....]
B = [15,14,....]

I can use split() and read them into separate lists but classification names have more than one word and I have to capture full name in the list instead of first word. Any suggestions would be appreciative.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just use zip() to transpose the matrix represented by the csv reader object:

import csv

with open(fn) as f:
    reader=csv.reader(f, delimiter='')
    a, b, c = zip(*reader)

    print a
    ('Classification Type', 'Commercial Homes', 'Residential Homes')
    print b
    ('A', '12', '10')
    print c
    ('B', '15', '14')
    # trim the tuples as you wish, such as b=list(b[1:])...

Then, you may want a dict with the first value of that tuple:

data={}
for t in zip(*reader):
    data[t[0]]=t[1:]

print data    
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}

Which then can be reduced to a single statement:

data={t[0]:t[1:] for t in zip(*reader)}
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...