【问题标题】:Read columns into separate lists将列读入单独的列表
【发布时间】:2014-08-22 15:16:30
【问题描述】:

我有一个超过 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() 并将它们读入单独的列表,但分类名称有多个单词,我必须在列表中捕获全名而不是第一个单词。任何建议将不胜感激。

【问题讨论】:

  • 用什么分隔列?制表符、空格、逗号?

标签: python list python-2.7


【解决方案1】:

这样的事情可能会奏效:

#!/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])

这有点冗长。但它通过数据一次完成工作。

【讨论】:

  • 我使用制表符分隔列。然后就可以了。
  • 啊!我错过了您在数据线上的领先 cmets 包含空格。默认情况下,Python .split() 字符串方法会在任何空白序列上拆分。您可以提供参数以拆分其他字符(但是,在这种情况下,只有单个字符,要拆分您将使用 re 模块中的方法的正则表达式)。正如其他人所说,要从 CSV(逗号分隔值)或类似格式的源中解析数据,请使用 csv 模块。 (我关注的是如何根据您的示例获取解析的数据并分离特定列的问题。
【解决方案2】:

只需使用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')}

【讨论】:

    【解决方案3】:

    使用 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()
    

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2015-11-12
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多