在Python中旋转二维数组 [英] Rotating a two-dimensional array in Python
问题描述
在一个程序中,我正在写一个旋转二维数组的需求.在寻找最佳解决方案时,我发现了这种令人印象深刻的一线功能:
In a program I'm writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job:
rotated = zip(*original[::-1])
我现在在程序中使用它,它按预期工作.我的问题是,我不了解它的工作原理.
I'm using it in my program now and it works as supposed. My problem though, is that I don't understand how it works.
如果有人能解释所涉及的不同功能如何达到期望的结果,我将不胜感激.
I'd appreciate if someone could explain how the different functions involved achieves the desired result.
推荐答案
请考虑以下二维列表:
original = [[1, 2],
[3, 4]]
让我们将其逐步分解:
>>> original[::-1] # elements of original are reversed
[[3, 4], [1, 2]]
此列表通过参数解压缩zip() >,因此zip
调用最终等同于此:
This list is passed into zip()
using argument unpacking, so the zip
call ends up being the equivalent of this:
zip([3, 4],
[1, 2])
# ^ ^----column 2
# |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise
希望注释能够清楚地说明zip
的作用,它将根据索引将来自每个可迭代输入的元素进行分组,或者换句话说,将列进行分组.
Hopefully the comments make it clear what zip
does, it will group elements from each input iterable based on index, or in other words it groups the columns.
这篇关于在Python中旋转二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!