简体   繁体   English

将数组的列向左移动

[英]Shifting columns of an array to the left

My goal is to shift the columns of an array B k positions to the left.我的目标是将数组B k位置的列向左移动。 Assume B is of the shape (n,n) .假设B的形状为(n,n) Then of course, the columns from n to nk have to replaced with some new entries.然后,当然,从nnk的列必须替换为一些新条目。 But this shouldn't be of importance here.但这在这里不应该很重要。 What does work is the following:起作用的是以下内容:

for i in range(n):
   for j in range(n-k):
      B[i][j]  = B[i][j+k]

I wonder if there is a faster and simpler method.我想知道是否有更快更简单的方法。 Any suggestions appreciated任何建议表示赞赏

If you were using your matrix in column-major order (ie using i as column index), much less copies would be needed如果您以列优先顺序使用矩阵(即使用i作为列索引),则需要更少的副本

for j in range(n-k):
   B[i] = B[i+k]

in this case only the reference to the column is copied在这种情况下,仅复制对列的引用

You could use subscripts:您可以使用下标:

B = B[k:] + newValues

or, if you want to keep the array size and manipulate the original positions afterward:或者,如果您想保持数组大小并在之后操作原始位置:

B[:k] = B[k:2*k]

note that, in this last approach, you must have 2k <= n otherwise you won't have enough elements to fill the left side of the array请注意,在最后一种方法中,您必须有 2k <= n 否则您将没有足够的元素来填充数组的左侧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM