gpt4 book ai didi

python - 移动Python数组中的行和列

转载 作者:行者123 更新时间:2023-12-02 20:04:28 24 4
gpt4 key购买 nike

我正在构建一个基本的绘图机器人,其中所有数据都存储在 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']

我已经弄清楚了每当在预定义数组之外检测到某些内容时如何扩展数组,但是我无法像上面演示的那样移动行和列。

任何帮助将不胜感激。谢谢:)

最佳答案

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]

关于python - 移动Python数组中的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com