【问题标题】:How to find dimension of a nested tuple?如何找到嵌套元组的维度?
【发布时间】:2016-03-11 10:23:30
【问题描述】:

我有一个像这样的元组

  array=(1,2,3,4)
  lenM = numpy.shape(array)
  print lenM
  (4,)

  if not lenM[1]:
       "Code"

现在我如何自动化我的代码来查找元组是一维还是二维?

【问题讨论】:

  • 元组和可以从它们构造的数组之间存在一些混淆。

标签: python-2.7 numpy tuples


【解决方案1】:
array=(1,2,3,4)
lenM = numpy.shape(array)
print lenM
(4,)

if len(lenM) == 1:
    "1 dimensional code"
elif len(lenM) == 2:
    "2 dimensional code"

len(lenM) 会告诉你数组中是否有多个维度。如果 len(lenM) 为 1,则只有一维。如果数组有多个维度,则 lenM 将有多个元素。

【讨论】:

  • 如果我不知道“a”的样子怎么办?我应该使用 len() 还是 np.shape()?
【解决方案2】:

您可以为此使用numpy.ndim

In [4]: np.ndim((1,2,3,4))
Out[4]: 1
In [5]: np.ndim(((1,2),(3,4)))
Out[5]: 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2014-12-13
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多