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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15985389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:31:55  来源:igfitidea点击:

python: check if list is multidimensional or one dimensional

pythonarraysnumpymultidimensional-array

提问by user2129468

I am currently programing in python and I created a method that inputs list from the user, without knowing whether he is multidimensional or one dimensional. how do I check? sample:

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



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

target is the list. the problem is that target[0] might be int.

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

回答by Hyman

I think you just want isinstance?

我想你只是想要isinstance

Example usage:

用法示例:

>>> 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

回答by lvc

According to the comments, you are converting your input to a numpy array anyway. Since np.arrayalready handles figuring out how deeply the input lists are nested, it is easier to find out the number of dimensions from that array than from the nested lists.

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

In particular, arrays have a shapeattribute which is a tuple of the lengths of the array along each dimension, so len(myarray.shape)will tell you the number of dimensions. eg,

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

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

回答by bunkus

If you like to find out how many dimensions a list has you can use this snippet of code:

如果你想知道一个列表有多少维度,你可以使用以下代码片段:

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)

回答by Ryan Jones

This is very simplified solution. In most cases a multi-dimensional list/array/matrix would contain a list object in the first index. That being said, in python since you don't need to define the data type, this could return incorrect if your list looks something link: [1, [2,3], 4]. -- Otherwise it should work for all normal multi-dimensional lists.

这是非常简化的解决方案。在大多数情况下,多维列表/数组/矩阵将在第一个索引中包含一个列表对象。话虽如此,在 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

See it in action: https://trinket.io/python/a937fe2f00

看看它在行动:https: //trinket.io/python/a937fe2f00