def get_list_dimension(lst):dimension = 0while isinstance(lst, list):dimension += 1if len(lst) > 0:lst = lstelse:breakreturn dimension示例列表lst1 = [1, 2, 3]print(get_list_dimension(lst1)) 输出: 1lst2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(get_list_dimension(lst2)) 输出: 2lst3 = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]print(get_list_dimension(lst3)) 输出: 3
2. 使用`numpy`库中的`ndim`属性来查看数组的维度。
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])print(arr.ndim) 输出: 2
3. 使用`numpy`库中的`shape`属性来查看数组的维度。

import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])print(arr.shape) 输出:(2, 3)
4. 使用自定义函数`test_dim`来判断列表的维度。
def test_dim(testlist, dim=0):if isinstance(testlist, list):if testlist == []:return dimdim = dim + 1return test_dim(testlist, dim)else:if dim == 0:return -1else:return dim示例列表a = []print(test_dim(a)) 输出: 0a = ["A"]print(test_dim(a)) 输出: 0a = ["A", "B", "C"]print(test_dim(a)) 输出: 0a = [[1, 2, 3], [1, 2, 3]]print(test_dim(a)) 输出: 1a = [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]print(test_dim(a)) 输出: 2
以上方法可以帮助您了解Python列表的维度。
