将列读入单独的列表 [英] Read columns into separate lists
本文介绍了将列读入单独的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,该文件有10行以上和3列,例如:
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,....]
我可以使用split()
并将它们阅读到单独的列表中,但是分类名称包含多个单词,我必须在列表中捕获全名而不是第一个单词.任何建议将是感激的.
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.
推荐答案
只需使用zip()
转置由csv阅读器对象表示的矩阵:
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='\t')
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')}
这篇关于将列读入单独的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文