【问题标题】:Reading a text file (tab/space delimited) having named columns into lists with the lists having the same name as the column name将具有命名列的文本文件(制表符/空格分隔)读取到列表中,列表名称与列名相同
【发布时间】:2022-01-14 09:42:20
【问题描述】:

我的文本文件如下所示:

x   y   z   D
0   0   350 10
50  -50 400 15
100 50  450 10
-25 100 500 10  

列是制表符分隔的。我想将它导入到具有列名的 4 个 Python 列表中:

x = [0, 50, 100, -25]
y = [0, -50, 50, 100]
z = [350, 400, 450, 500]
D = [10, 15, 10, 10]

是否可以使用一些内置函数来做到这一点,而无需导入 Pandas 或一些特殊的包?

【问题讨论】:

  • 使用 csv 模块。

标签: python parsing file-handling


【解决方案1】:

你可以这样做:

import re
with open('file.txt') as f:
    data = [re.split('[ ]+|\t',x) for x in f.read().split('\n')]
res = dict((x,[]) for x in data[0])
for i in data[1:]:
    for j in range(len(i)):
        res[data[0][j]].append(i[j])
print(res)

【讨论】:

    【解决方案2】:

    我建议这种方法...

    构造一个以列名 (x, y, z, D) 为键的字典

    每个键都有一个值,它是一个列表。

    使用将单个值附加到相应键的文件。

    from collections import defaultdict
    with open('t.txt') as infile:
        cols = next(infile).strip().split()
        d = defaultdict(list)
        for line in infile:
            for i, t in enumerate(line.strip().split()):
                d[cols[i]].append(int(t))
        for k, v in d.items():
            print(f'{k} = {v}')
    

    输出

    x = [0, 50, 100, -25]
    y = [0, -50, 50, 100]
    z = [350, 400, 450, 500]
    D = [10, 15, 10, 10]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 2017-09-03
      • 1970-01-01
      相关资源
      最近更新 更多