python:检查列表是多维还是一维

use*_*468 7 python arrays numpy multidimensional-array

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


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

target是列表.问题是target [0]可能是int.

Jac*_*ack 13

我想你只想要实例

用法示例:

>>> 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
Run Code Online (Sandbox Code Playgroud)


lvc*_*lvc 10

根据评论,您无论如何都要将输入转换为numpy数组.由于np.array已经处理了输入列表嵌套的深度,因此更容易从该数组中找出维度的数量而不是嵌套列表.

特别是,数组的shape属性是沿每个维度的数组长度的元组,因此len(myarray.shape)将告诉您维度的数量.例如,

>>> import numpy as np
>>> a = np.array([[1,2,3],[1,2,3]])
>>> len(a.shape)
2
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`len(a.shape)== a.ndim`. (6认同)

bun*_*kus 7

如果您想了解列表有多少维度,可以使用以下代码片段:

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)
Run Code Online (Sandbox Code Playgroud)