0

我必须读入一个文件,例如:

0,11,6,0,10x11,0,5,4,7x6,5,0,2,3x0,4,2,0,12x10,7,3,12,0

所以我必须把它读入一个二维数组。

这是我的代码:

    //set delimiter to commas
     String r1=",";
     String r2="x";
     input.useDelimiter(r2);
     //print file to check contents
     while(input.hasNext()){

         System.out.print(input.next());
     }

     //transfer file into matrix
     int[][] graph=new int[filelength][filelength];
     for (int row=0; row<graph.length;row++){
         for(int column=0; column<graph[row].length;column++){
             graph[row][column]=input.nextInt();
         }
     }

     }
    //close file
     input.close();
}

}

我遗漏了我的代码的细节。但是我正在使用扫描仪类,并且我正在尝试使用两个定界符,以便在定界符“x”上代码更改为矩阵的另一行,在定界符“”上,代码输入矩阵的条目。

4

1 回答 1

0

在 Python 中,如果您可以将数据存储为列表列表以制作二维数组,那么您可以读取文件数据,这里表示为字符串,然后执行以下操作:

>>> from pprint import pprint
>>> filedata = '0,11,6,0,10x11,0,5,4,7x6,5,0,2,3x0,4,2,0,12x10,7,3,12,0'
>>> array2d = [row.split(',') for row in filedata.split('x')]
>>> pprint(array2d)
[['0', '11', '6', '0', '10'],
 ['11', '0', '5', '4', '7'],
 ['6', '5', '0', '2', '3'],
 ['0', '4', '2', '0', '12'],
 ['10', '7', '3', '12', '0']]
>>> array2d[0]
['0', '11', '6', '0', '10']
>>> array2d[1]
['11', '0', '5', '4', '7']
>>> array2d[1][2]
'5'
>>> 

如果你想要实际的整数,你可以这样做:

>>> arrayints = [[int(item) for item in row.split(',')] for row in filedata.split('x')]
>>> pprint(arrayints)
[[0, 11, 6, 0, 10],
 [11, 0, 5, 4, 7],
 [6, 5, 0, 2, 3],
 [0, 4, 2, 0, 12],
 [10, 7, 3, 12, 0]]
>>> arrayints[1][2]
5
>>> 
于 2013-05-08T19:05:23.607 回答