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

时间:2016-01-08 12:00:09

标签: 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;

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

此。

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]]]

答案 1 :(得分:1)

试试这个:

with open('file.txt') as f:
    Items = []
    Reg = []
    count = -1
    file_list = f.read().strip().split('\n')
    for line in file_list:
        if 'Item1' in line:
            Items.append([])
            count += 1
        if 'Region' in line:
            Reg.append(line.split(": ")[-1])

        # there is a space at the beginning of the line
        if line[1].isdigit():
            ints = [int(j) for j in line.split()]
            Items[count].append(ints)
    print(Items)
    print(Reg)