Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 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 Reply

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')}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...