在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`属性来查看数组的维度。
import numpy as np
arr = 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 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)) 输出: 2
以上方法可以帮助您了解Python列表的维度。