在Python中,查看列表或数组的维度可以通过以下几种方法:
1. 使用`len()`函数和递归方法来判断列表的维度:
def get_list_dimension(lst):
dimension = 0
while isinstance(lst, list):
dimension += 1
if len(lst) > 0:
lst = lst
else:
break
return dimension
示例列表
lst1 = [1, 2, 3]
print(get_list_dimension(lst1)) 输出: 1
lst2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(get_list_dimension(lst2)) 输出: 2
lst3 = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
print(get_list_dimension(lst3)) 输出: 3
2. 使用`numpy`库中的`ndim`属性来查看数组的维度:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim) 输出: 2
3. 将列表转化为`numpy`数组后,使用`shape`属性查看数组的维度:
a = [] 一维
b = [[1, 2], [3, 4]] 二维
print(len(np.array(a).shape)) 输出: 0
print(len(np.array(b).shape)) 输出: 2
4. 自定义函数`test_dim`来判断列表的维度数:
def test_dim(testlist, dim=0):
if isinstance(testlist, list):
if testlist == []:
return dim
dim = dim + 1
return test_dim(testlist, dim)
else:
if dim == 0:
return -1
else:
return dim
a = []
print(test_dim(a)) 输出: 0
a = ["A"]
print(test_dim(a)) 输出: 0
a = ["A", "B", "C"]
print(test_dim(a)) 输出: 0
a = [[1, 2, 3], [1, 2, 3]]
print(test_dim(a)) 输出: 1
a = [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]
print(test_dim(a)) 输出: 3
以上方法可以帮助你了解Python中数据结构的维度。