将已命名列的文本文件(tab/space 分隔)读取到列表中,列表的名称与列名相同
Reading a text file (tab/space delimited) having named columns into lists with the lists having the same name as the column name
我的文本文件如下所示:
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 或某些特殊包?
我建议这种方法...
构造一个以列名 (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]
你可以这样做:
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)
我的文本文件如下所示:
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 或某些特殊包?
我建议这种方法...
构造一个以列名 (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]
你可以这样做:
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)