python中数据纬度的含义_python数组维度怎么看

python中数据纬度的含义_python数组维度怎么看在 Python 中 查看列表或数组的维度可以通过以下几种方法 1 使用 len 函数和递归方法来判断列表的维度 pythondef get list dimension lst dimension 0 while isinstance lst list dimension 1 if len lst 0 lst lst else break

在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中数据结构的维度。

编程小号
上一篇 2025-01-19 08:08
下一篇 2025-01-19 08:04

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/134251.html