【发布时间】:2020-11-02 19:19:02
【问题描述】:
我还是python的初学者,想把这段用Java写的代码转成Python
// shifts the element of each row according to the row's index and the element's
// index in the row example row 0 no shifts ( since all the elements would get
// their original positions from this formula [(i+j) % d] row 1, one shift for all
// the elements, and so on for all the rows in the array using the same formula
public void doSomething(int[][] a) {
int[] temp = new int[d];
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
temp[j] = a[i][(j + i) % a[i].length];
}
System.arraycopy(temp, 0, a[i], 0, a[i].length);
}
}
我尝试了类似的方法:
def do_something(self, arr):
temp_list = []
i = 0
for row in arr:
j = 0
for _ in row:
y = (i + j) % self.d
z = arr[i, y]
temp_list.append(z)
j += 1
arr[i, :] = temp_list
i += 1
return arr
我收到此错误:
arr[i, :] = temp_list
ValueError: cannot copy sequence with size 8 to array axis with dimension 4
对于输入数组:
0 1 2
3 4 5
6 7 8
应该会得到结果:
0 1 2
4 5 3
8 6 7
或者对于这个输入:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
这个输出
0 1 2 3
5 6 7 4
10 11 8 9
15 12 13 14
【问题讨论】:
-
能否提供输入输出示例?
-
我已经更新了问题
标签: java python python-3.x numpy multidimensional-array