【问题标题】:Incremental rolling function on nested lists嵌套列表上的增量滚动功能
【发布时间】: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


【解决方案1】:

这是一个可以完成这项工作的快速小功能。本质上,每个子数组都按其在父数组中的索引进行移位。

设置:

l1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
l2 = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17]]
l3 = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]

功能:

def spiral(array):
    temp = []
    for i, a in enumerate(array):
        n = i % len(a)
        temp.append(a[n:] + a[:n])
        n += 1
    return temp

输出:

>>> spiral(l1)
[[0, 1, 2], [4, 5, 3], [8, 6, 7]]

>>> spiral(l2)
[[0, 1, 2], [4, 5, 3], [8, 6, 7], [9, 10, 11], [13, 14, 12], [17, 15, 16]]

>>> spiral(l3)
[[0, 1, 2, 3], [5, 6, 7, 4], [10, 11, 8, 9], [15, 12, 13, 14]]

编辑:

根据 OP 的 cmets,更新函数以简化并确保与不同长度的嵌套列表兼容。

【讨论】:

  • 从逻辑上讲,我认为这不太对!不适用于不同大小的数组,我在 4x4 上尝试过,最后一行没有改变
  • 好的;会看看。如果有原始问题中没有的任何要求(或实施细节),请相应更新。
  • 我再次更新了这个问题,提供了更多细节:)
  • 太好了,谢谢伙计。答案已更新,现在显示与不同长度的嵌套列表的兼容性。
  • 这太好了,非常感谢!还有一个问题,您的代码在 Jupyter Notebook 上运行良好,但在我的 PyCharm 项目中却不行,我得到“ temp.append(a[n:] + a[:n]) ValueError: operands could not be broadcast together with shapes ( 4,) (0,) "
猜你喜欢
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多