如何确定列表的维度?

Sti*_* HK 1 python list multidimensional-array

如何以编程方式确定列表的维度?谢谢.

Cla*_*diu 7

对于简单的列表,您可以通过以下方式获取其长度len:

>>> l = [1, 2, 3, 4, 5]
>>> len(l)
5
Run Code Online (Sandbox Code Playgroud)

对于最容易表示为嵌套列表的矩阵,您可以获得第一个子列表的长度,例如:

>>> matrix = [
    [1, 2],
    [3, 4],
    [5, 6],
    [7, 8],
    [9, 10]]
>>> len(matrix)
5
>>> len(matrix[0])
2
Run Code Online (Sandbox Code Playgroud)

考虑到JBernardo的评论,定义一个简单的iterable帮助器:

>>> def iterable(x):
    if isinstance(x, basestring): return False
    try:
        iter(x)
    except TypeError:
        return False
    return True

>>> iterable(4)
False
>>> iterable([1, 2, 3])
True
Run Code Online (Sandbox Code Playgroud)

然后我们可以递归地定义dimensionality函数:

>>> def dimensionality(l):
    if not iterable(l): return 0
    return 1 + dimensionality(l[0])

>>> dimensionality(0)
0
>>> dimensionality([1, 2, 3])
1
>>> dimensionality([[1,2], [2,3], [3,4]])
2
>>> dimensionality([[[1,2],[2,3]], [[2,3],[3,4]], [[3,4],[4,5]]])
3
Run Code Online (Sandbox Code Playgroud)

而不是iterable你可以做isinstance(x, list)或任何其他你想要的检查.编辑以排除字符串以避免dimensionality('lol')无限循环.

  • `维度('lol')` - >无限循环.确保排除字符串. (2认同)