【问题标题】:python: check if list is multidimensional or one dimensionalpython:检查列表是多维还是一维
【发布时间】:2013-04-05 19:24:52
【问题描述】:

我目前正在使用 python 编程,我创建了一个从用户输入列表的方法,不知道他是多维还是一维。我该如何检查? 示例:


def __init__(self,target):    
    for i in range(len(target[0])):
        w[i]=np.random.rand(len(example[0])+1)

目标是列表。问题是 target[0] 可能是 int。

【问题讨论】:

  • 您需要更具体地了解用户如何输入“数组”。
  • 是的,有很多方法可以做到这一点,显示您的示例输入是什么样的
  • 你是对的。用户首先输入一个列表,我将其转换为数组。
  • @user2129468 请显示一些实际代码
  • Python 列表只是一维的。 “多维”是什么意思?嵌套列表?请给我们举个例子。

标签: python arrays numpy multidimensional-array


【解决方案1】:

我想你只是想要isinstance

示例用法:

>>> a = [1, 2, 3, 4]
>>> isinstance(a, list)
True
>>> isinstance(a[0], list)
False
>>> isinstance(a[0], int)
True
>>> b = [[1,2,3], [4, 5, 6], [7, 8, 9]]
>>> isinstance(b[0], list)
True

【讨论】:

  • OP 询问如何区分一维数组与多维数组,而不是数组与数字
  • @feresr 重新阅读我的答案。它一维数组与多维数组...注意[0]
  • 哦,你是对的@Jack,我的错误很抱歉!
【解决方案2】:

根据 cmets,无论如何,您正在将输入转换为 numpy 数组。由于np.array 已经处理了计算输入列表嵌套的深度,因此从该数组中找出维数比从嵌套列表中更容易。

特别是,数组有一个shape 属性,它是数组沿每个维度的长度的元组,所以len(myarray.shape) 会告诉你维数。例如,

>>> import numpy as np
>>> a = np.array([[1,2,3],[1,2,3]])
>>> len(a.shape)
2

【讨论】:

  • 其实len(a.shape) == a.ndim.
【解决方案3】:

如果你想知道一个列表有多少维,你可以使用这个 sn-p 代码:

def test_dim(testlist, dim=0):
   """tests if testlist is a list and how many dimensions it has
   returns -1 if it is no list at all, 0 if list is empty 
   and otherwise the dimensions of it"""
   if isinstance(testlist, list):
      if testlist == []:
          return dim
      dim = dim + 1
      dim = test_dim(testlist[0], dim)
      return dim
   else:
      if dim == 0:
          return -1
      else:
          return dim
a=[]
print test_dim(a)
a=""
test_dim(a)
print test_dim(a)
a=["A"]
print test_dim(a)
a=["A", "B", "C"]
print test_dim(a)
a=[[1,2,3],[1,2,3]]
print test_dim(a)
a=[[[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]]]
print test_dim(a)

【讨论】:

    【解决方案4】:

    这是一个非常简单的解决方案。在大多数情况下,多维列表/数组/矩阵将在第一个索引中包含一个列表对象。话虽如此,在 python 中,因为您不需要定义数据类型,如果您的列表看起来像链接:[1,[2,3],4],这可能会返回不正确。 -- 否则它应该适用于所有正常的多维列表。

    def is2DList(matrix_list):
      if isinstance(matrix_list[0], list):
        return True
      else:
        return False
    # list
    list_1 = [1,2,3,4] # 1 x 4
    list_2 = [ [1,2,3],[3,4,5] ] # 2 x 2
    list_3 = [1, [2,3], 4]
    
    print(is2DList(list_1)) # False
    print(is2DList(list_2)) # True
    print(is2DList(list_3)) # False - incorrect result
    

    查看实际操作:https://trinket.io/python/a937fe2f00

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 2020-08-03
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多