在Python中旋转二维数组 [英] Rotating a two-dimensional array in Python

查看:106
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆