我的文本檔案如下所示:
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 或一些特殊的包?
uj5u.com熱心網友回復:
你可以這樣做:
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)
uj5u.com熱心網友回復:
我建議這種方法...
構造一個以列名 (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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411945.html
標籤:
