简体   繁体   English

在python数组中移动行和列

[英]Shifting rows and columns in a python array

I'm building a basic mapping robot where all the data is stored on a 2D python array. 我正在构建一个基本的映射机器人,其中所有数据都存储在2D python数组中。 However I am unable to find any way to move entire rows or columns over and then insert a blank row/column in. For example: 但是,我找不到任何方法可以移动整个行或列,然后在其中插入空白行/列。例如:

['#','0','0']        
['0','1','0']                                            
['#','0','0']

if moved to the right to look like : 如果移到右边,看起来像:

['0','#','0']        
['0','0','1']                                            
['0','#','0']

or 要么

['#','0','#']         
['0','1','0']                                     
['0','0','0']                                     

if moved down to look like : 如果向下移动看起来像:

['0','0','0']         
['#','0','#']                                     
['0','1','0']

I have already figured out how to expand the array whenever something is detected outside of the pre-defined array however I am unable to move rows and columns like demonstrated above. 我已经想出了每当在预定义数组之外检测到某些东西时如何扩展数组,但是我无法像上面演示的那样移动行和列。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks :) 谢谢 :)

Have you looked at numpy and numpy.roll for this? 您是否为此查看过numpy和numpy.roll?

import numpy as np
a = np.array([['#','0','0'],
['0','1','0'],                                           
['#','0','0']])

then you can shift right: 那么您可以右移:

a = np.roll(a,1)
a[:,0] = 0

shift left: 左移:

a = np.roll(a,-1)
a[:,-1] = 0

shift up: 上移:

a = np.roll(a,-1,axis = 0)
a[-1,:] = 0

shift down: 降档:

a = np.roll(a,1,axis = 0)
a[0,:] = 0

You can create a class to handle this movements like this: 您可以创建一个类来处理这种运动,如下所示:

class Board(object):
    def __init__(self, rows):
        self.rows = rows
        self.print_status()

    def print_status(self):
        for row in self.rows:
            print(row)

    def right(self):
        new_rows = []
        for row in self.rows:
            row = row[-1:] + row[:len(row)-1]
            new_rows.append(row)
        self.rows = new_rows
        self.print_status()

    def left(self):
        new_rows = []
        for row in self.rows:
            row = row[1:] + row[:1]
            new_rows.append(row)
        self.rows = new_rows
        self.print_status()

    def up(self):
        new_rows = []
        for row in self.rows[1:]:
            new_rows.append(row)
        new_rows.append(self.rows[0])
        self.rows = new_rows
        self.print_status()

    def down(self):
        new_rows = []
        new_rows.append(self.rows[-1])
        for row in self.rows[:-1]:
            new_rows.append(row)
        self.rows = new_rows
        self.print_status()

Example: 例:

>>> a = Board([[1,2,3],[4,5,6],[7,8,9]])
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

>>> a.down()
[7, 8, 9]
[1, 2, 3]
[4, 5, 6]

>>> a.up()
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

>>> a.right()
[3, 1, 2]
[6, 4, 5]
[9, 7, 8]

This can be easily done by "roll" function from numpy 这可以通过numpy的“ roll”功能轻松完成
example in your case: 您的示例:

import numpy as np
a = np.array([['#','0','0'], ['0','1','0'], ['#','0','0']])

output will be: 输出将是:

array([['#', '0', '0'],
   ['0', '1', '0'],
   ['#', '0', '0']], dtype='<U1')

for 1st usecase: 对于第一个用例:

np.roll(a, 1, 1)

output will be 输出将是

array([['0', '#', '0'],
   ['0', '0', '1'],
   ['0', '#', '0']], dtype='<U1')

for second case yo can simply take transpose: 对于第二种情况,您可以简单地转置:

a.T

and output will be 和输出将是

array([['#', '0', '#'],
   ['0', '1', '0'],
   ['0', '0', '0']], dtype='<U1')

Third case be done by applying numpy roll operation on transpose matrix 第三种情况是对转置矩阵应用numpy roll操作

np.roll(a.T, 1, 0)

output 产量

array([['0', '0', '0'],
   ['#', '0', '#'],
   ['0', '1', '0']], dtype='<U1')

The numpy solutions work great, but here is a solution in pure Python, with no imports. numpy解决方案效果很好,但是这里是纯Python解决方案,没有导入。 Note that most of this code just prints the results--each roll uses only one line of code. 请注意,大多数代码仅打印结果-每卷仅使用一行代码。 I also added shiftedup , where the matrix is rotated up then the last row is replaced with all zeros (though it is done more efficiently than that). 我还添加了shiftedup ,将矩阵向上旋转,然后将最后一行替换为全零(尽管比这更有效)。

myarray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
print('\nOriginal:')
for row in myarray:
    print(row)

rolledup = myarray[1:] + myarray[:1]
print('\nRolled up:')
for row in rolledup:
    print(row)

rolleddown = myarray[-1:] + myarray[:-1]
print('\nRolled down:')
for row in rolleddown:
    print(row)

rolledleft = [row[1:] + row[:1] for row in myarray]
print('\nRolled left:')
for row in rolledleft:
    print(row)

rolledright = [row[-1:] + row[:-1] for row in myarray]
print('\nRolled right:')
for row in rolledright:
    print(row)

shiftedup= myarray[1:] + [[0] * len(myarray[0])]
print('\nShifted up:')
for row in shiftedup:
    print(row)

The printout from that is: 从中打印输出为:

Original:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Rolled up:
[4, 5, 6]
[7, 8, 9]
[1, 2, 3]

Rolled down:
[7, 8, 9]
[1, 2, 3]
[4, 5, 6]

Rolled left:
[2, 3, 1]
[5, 6, 4]
[8, 9, 7]

Rolled right:
[3, 1, 2]
[6, 4, 5]
[9, 7, 8]

Shifted up:
[4, 5, 6]
[7, 8, 9]
[0, 0, 0]

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

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