我正在构建一个基本的映射机器人,其中所有数据都存储在2D python数组中。但是,我找不到任何方法可以移动整个行或整个列,然后在其中插入空白行/列。例如:
['#','0','0']
['0','1','0']
['#','0','0']
如果移到右侧看起来像:
['0','#','0']
['0','0','1']
['0','#','0']
或
['#','0','#']
['0','1','0']
['0','0','0']
如果下移为:
['0','0','0']
['#','0','#']
['0','1','0']
我已经想出了只要在预定义的数组之外检测到某种东西就如何扩展数组,但是我无法像上面演示的那样移动行和列。
任何帮助将不胜感激。谢谢:)
答案 0 :(得分:1)
您是否为此查看过numpy和numpy.roll?
import numpy as np
a = np.array([['#','0','0'],
['0','1','0'],
['#','0','0']])
然后您可以右移:
a = np.roll(a,1)
a[:,0] = 0
左移:
a = np.roll(a,-1)
a[:,-1] = 0
上移:
a = np.roll(a,-1,axis = 0)
a[-1,:] = 0
下移:
a = np.roll(a,1,axis = 0)
a[0,:] = 0
答案 1 :(得分:0)
您可以创建一个类来处理此类运动:
var readlineSync = require('readline-sync');
var years = readlineSync.questionInt('Enter the number of years: ');
for (i = 0; i < years; i++) {
for (j = 0; j < 11; j++) {
var monthlyrainfall = readlineSync.questionInt('How many inches of rainfall was there this month? ');
}
}
示例:
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()
答案 2 :(得分:0)
numpy解决方案效果很好,但这是纯Python的解决方案,没有导入。请注意,大多数代码仅打印结果-每卷仅使用一行代码。我还添加了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)
打印出来的是:
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]