python - 从文件中读取整数并将整数保存到列表 Python

标签 python arrays list text-files

我在 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/

相关文章:

r - 以 R 中的元素数量为条件删除列表

python - 如何检查字符串列表中是否存在字符串,包括子字符串?

python - Python中的方括号和点符号有什么区别?

python - 乘以 Numpy 矩阵的列时出现问题

ios - 排序数组导致错误的数据显示到单元格中

ruby - 在 ruby​​ 中创建文件数组并按日期排序

python - 在没有循环的情况下在 Numpy 中切片一维数组

python - if else 在列表理解中

python - Pandas/Python - 数据帧和字典之间的多重条件匹配

python - 根据多个范围从数组中检索间隔