我必须阅读如下文件:
0,11,6,0,10x11,0,5,4,7x6,5,0,2,3x0,4,2,0,12x10,7,3,12,0
所以我必须把它读成2d数组。
这是我的代码:
//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'上代码更改为矩阵的另一行和分隔符“,”代码输入矩阵的输入。
答案 0 :(得分:0)
在Python中,如果你可以将数据存储为列表列表来制作2d数组,那么你可以读入文件数据,这里用字符串表示,并执行以下操作:
>>> 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
>>>