我正在嘗試讀取具有以下結構的文本檔案:
BUS 0
0 1 2 3
0 4 1 9 2 3
BUS 1
0 1 9 2 3
0 1 2 3
0 1 2 3
它基本上是一個 3D 串列,其中嵌套的 2D 串列是列數和行數不相等的矩陣。第一個索引由字串“BUS”表示,后跟一個數字。接下來的幾行對應一個二維串列,每一行都是一個串列,直到下一個“BUS”字串。我需要將此文本檔案中的數字分配給 Python 中的 3D 串列。上面給出的示例應轉換為:
[ [ [[0,1,2,3],[0,4,1,9,2,3]], [[0,1,9,2,3],[0,1,2,3], [0,1,2,3] ] ]
在此先感謝您的幫助。
uj5u.com熱心網友回復:
您可以嘗試以下操作:
data = []
with open("file.wtv") as file_in:
for line in file_in:
try:
row = [*map(int, line.strip().split())]
data[-1].append(row)
except ValueError:
data.append([])
data
# [[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]],
# [[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]
uj5u.com熱心網友回復:
您需要撰寫一個簡單的決議器:
test = '''BUS 0
0 1 2 3
0 4 1 9 2 3
BUS 1
0 1 9 2 3
0 1 2 3
0 1 2 3'''
out = []
for line in test.split('\n'):
if line.startswith('BUS'):
out.append([])
else:
out[-1].append(list(map(int, line.split())))
輸出:
[[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]],
[[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]
從檔案:
with open('file.txt') as f:
out = []
for line in f:
if line.startswith('BUS'):
out.append([])
else:
out[-1].append(list(map(int, line.split())))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/337860.html
下一篇:索引值不在串列中
