我在 Python 中遇到多维数组问题(MATLAB 让它看起来很简单......)。我需要从具有以下外观的 .txt
文件中读取数字:
Region: Boston
Item1 Item2
0 100
13 100
27 62
41 51
-----------
Region: Chicago
Item1 Item2
0 30
15 50
35 70
45 1
我是 Python 新手,我正在努力读取数据并将其保存到列表中。 我已成功执行以下操作:
lines = [line.strip() for line in open(fileRadiance, 'r')]
for i in xrange(0, len(lines)):
words = lines[i].split(); #Separates by whitespaces
if words[0] == "Region":
Reg[Regcounter:] = words[2:]
bsaveData = True;
if (bsaveData):
Items[Itemcounte][0] = int(words[0]); Items[Itemcounte][1] = int(words[0]);
---or---
Items[Itemcounter:] = words;
Itemcounter+=1;
他们都没有生产出我想要的东西,而且我仍然没有与第二个区域进行战斗。我希望将它们作为整数放在这样的列表中:
Items = [ [ [0,100],[13,100],[27,62],[41,51] ] , [ [0,30],[15,50],[35,70],[45,1] ] ]
所以如果我愿意的话:
Items[1][0][1] = 30;
Items[1][0][1] + Items[0][2][0] = 57;
有什么想法吗?
最佳答案
这个。
lines = [line.strip() for line in open('fileRadiance.txt', 'r')]
Reg = []
Items = []
for line in lines:
if "Item1" in line or '-----' in line:
continue
words = line.split()
if words[0] == "Region:":
Reg.append(words[1])
Items.append([])
else:
Items[-1].append([int(i) for i in words])
输出:
print Reg
>> ['Boston', 'Chicago']
print Items
>>[[[0, 100], [13, 100], [27, 62], [41, 51]], [[0, 30], [15, 50], [35, 70], [45, 1]]]
关于python - 从文件中读取整数并将整数保存到列表 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34676651/