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

查看:32
本文介绍了在 Python 中旋转二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我编写的程序中,出现了旋转二维数组的需要.在寻找最佳解决方案的过程中,我发现了这个令人印象深刻的单线,可以完成这项工作:

rotated = zip(*original[::-1])

我现在在我的程序中使用它,它按预期工作.不过我的问题是我不明白它是如何工作的.

如果有人能解释所涉及的不同功能如何达到预期的结果,我将不胜感激.

解决方案

考虑以下二维列表:

original = [[1, 2],[3, 4]]

让我们一步一步地分解:

<预><代码>>>>original[::-1] # 原始元素被反转[[3, 4], [1, 2]]

这个列表被传递到 zip() 使用 参数解包,所以 zip 调用最终等同于这个:

zip([3, 4],[1, 2])# ^ ^----第2列# |-------第1列# 返回[(3, 1), (4, 2)],这是一个顺时针旋转的原件

希望注释能说明 zip 的作用,它将根据索引对每个输入可迭代的元素进行分组,或者换句话说,它对列进行分组.

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.

解决方案

Consider the following two-dimensional list:

original = [[1, 2],
            [3, 4]]

Lets break it down step by step:

>>> original[::-1]   # elements of original are reversed
[[3, 4], [1, 2]]

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

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天全站免登陆