【问题标题】:Which of these two numpy slices are better to use?这两个 numpy 切片中哪个更好用?
【发布时间】:2017-07-09 02:02:19
【问题描述】:

我正在通过在线课程学习 Python。我们被要求对一个 6x6 的 numpy 数组进行切片并得到对角线。作为一个小组,我们开发了两种方法,如下所示。这个比那个好吗?

import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)

找到解决方案

six[::7]
six.reshape(36)[::7]

我的答案都返回array([ 1, 15, 29, 43, 57, 71])

我喜欢第一个,我的搭档喜欢第二个。任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 检查six的形状。我不认为它是 6x6。

标签: python arrays numpy slice


【解决方案1】:
six.reshape(6,6)

不修改six 本身:它只是返回一个新的二维数组,但保持six 不变。所以,你的两种方法实际上是一种方法。

您可以通过以下方式验证这一点:

>>> six = np.arange(1, 73, 2)
>>> six.reshape(6,6)
>>> print(six)

你会得到一个像这样的一维数组:

[ 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71]

因此,我声明不使用 unnecessary reshape 调用的答案(假设 six 是使用 np.arange(1, 73, 2) 创建的平面数组)是最佳答案 :)

【讨论】:

    【解决方案2】:

    让我们先修正一下你的代码,让它按照你的意图去做:

    six = np.arange(1, 73, 2).reshape(6, 6)
    

    现在比较你的方法:

    >>> six[::7]
    array([[ 1,  3,  5,  7,  9, 11]])
    

    致您的伴侣:

    >>> six.reshape(36)[::7]
    array([ 1, 15, 29, 43, 57, 71])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多