python中的矩阵镜像

新手上路,请多包涵

我有一个数字矩阵:

 [[a, b, c]
 [d, e, f]
 [g, h, i]]

我希望得到相应的镜像:

 [[g, h, i]
 [d, e, f]
 [a, b, c]
 [d, e, f]
 [g, h, i]]

然后再次屈服:

 [[i, h, g, h, i]
 [f, e, d, e, f]
 [c, b, a, b, c]
 [f, e, d, e, f]
 [i, h, g, h, i]]

我想坚持使用像 numpy 这样的基本 Python 包。在此先感谢您的帮助!

原文由 Sterling Butters 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 629
2 个回答

这可以在纯 python 中使用一个简单的辅助函数来完成:

 def mirror(seq):
    output = list(seq[::-1])
    output.extend(seq[1:])
    return output

inputs = [
   ['a', 'b', 'c'],
   ['d', 'e', 'f'],
   ['g', 'h', 'i'],
]
print(mirror([mirror(sublist) for sublist in inputs]))

显然,一旦创建了镜像列表,您就可以使用它来创建一个 numpy 数组或其他任何东西……

原文由 mgilson 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 numpy.lib.pad'reflect'

 m = [['a', 'b', 'c'],
     ['d', 'e', 'f'],
     ['g', 'h', 'i']]

n=np.lib.pad(m,((2,0),(2,0)),'reflect')

n
Out[8]:
array([['i', 'h', 'g', 'h', 'i'],
       ['f', 'e', 'd', 'e', 'f'],
       ['c', 'b', 'a', 'b', 'c'],
       ['f', 'e', 'd', 'e', 'f'],
       ['i', 'h', 'g', 'h', 'i']],
      dtype='<U1')

原文由 Daniel F 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题