用python实现看list的形状
时间: 2023-10-07 09:14:29 浏览: 61
以下是检查列表形状的Python代码:
```python
def check_shape(lst):
shape = []
while isinstance(lst, list):
shape.append(len(lst))
lst = lst[0]
return tuple(shape)
# 示例
lst = [[1, 2], [3, 4], [5, 6]]
print(check_shape(lst)) # 输出 (3, 2)
```
这个函数接受一个嵌套列表作为参数,并返回一个元组,其中每个元素表示列表在相应维度上的大小。例如,如果列表是 `[[1, 2], [3, 4], [5, 6]]`,则形状为 `(3, 2)`,表示它有三行和两列。
相关问题
python中list修改形状
在Python中,您可以使用 numpy 库来修改列表的形状。下面是一个示例代码,演示如何将一个3x3的列表转换为一个9元素的一维列表,然后再将其转换回一个3x3的列表。
```python
import numpy as np
# 创建一个3x3的列表
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 将列表转换为一维数组
my_array = np.array(my_list).flatten()
# 打印一维数组
print(my_array)
# 将一维数组转换回3x3的列表
new_list = my_array.reshape(3, 3)
# 打印新的3x3列表
print(new_list)
```
输出结果如下:
```
[1 2 3 4 5 6 7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
```
在这个示例中,我们首先使用 `numpy` 将原始列表转换为一维数组。然后,我们使用 `reshape` 方法将一维数组重新转换为3x3的列表。
python查看tuple的形状
tuple是一种不可变的有序序列,因此它的形状是由其中元素的个数和类型所决定的。你可以使用内置函数`len()`来查看tuple中元素的个数,例如:
```python
t = (1, 2, 3, 4, 5)
print("Tuple t has length:", len(t))
```
输出结果为:
```
Tuple t has length: 5
```
如果你想查看tuple中元素的类型,可以使用内置函数`type()`和Python的切片操作,例如:
```python
t = (1, 2, "three", [4, 5])
for i in range(len(t)):
print("The type of element", i, "is", type(t[i]))
```
输出结果为:
```
The type of element 0 is <class 'int'>
The type of element 1 is <class 'int'>
The type of element 2 is <class 'str'>
The type of element 3 is <class 'list'>
```