将列读取到独立列表中
我有一个文本文件,里面有超过10行和3列的数据,格式像这样:
Classification Type A B
Commercial Homes 12 15
Residential Homes 10 14
................ .. ..
我想把每一列单独读取出来,像这样:
Classification = ['Commercial Homes', 'Residential Homes'.......]
A = [12,10,....]
B = [15,14,....]
我可以用 split()
方法把它们分开,读到不同的列表里,但分类名称有好几个词,我需要把完整的名称都捕捉到列表里,而不是只取第一个词。有没有什么好的建议呢?
3 个回答
0
像这样可能会有效:
#!/usr/bin/python
with open('./mydata', 'r') as raw_data:
data = [line.strip().split() for line in raw_data.readlines()]
header = data.pop(0) ## Pop off header, removed from list
a = [record[1] for record in data]
b = [record[2] for record in data]
显然,我们要遍历这个列表两次,一次是为了 a
,另一次是为了 b
。对于小的数据集来说,这样做不会有什么性能问题。
另外,我们也可以这样做:
#!/usr/bin/python
a = list()
b = list()
with open('./mydata', 'r') as raw_data:
for line in raw_data:
if line.startswith('Classification'):
continue # skip the header line
line = line.strip().split()
a.append(line[1])
b.append(line[2])
这个方法稍微复杂一点,但它只需要一次遍历就能完成工作。
0
使用csv库来完成这个任务
import csv
def main():
with open(r'CSVReaderData.txt', 'r') as f:
reader = csv.reader(f, delimiter='\t')
col1, col2, col3 = zip(*reader)
print 'Classification = ',list(col1)
print 'A = ',list(col2)
print 'B = ',list(col3)
if __name__ == '__main__':
main()
4
只需要用 zip()
函数就可以把用 csv 读取器对象表示的矩阵进行转置:
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:])...
接着,你可能想要一个字典,其中包含那个元组的第一个值:
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')}
这样的话,就可以简化成一句话:
data={t[0]:t[1:] for t in zip(*reader)}
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}