如何遍历并打印列表中所有NumPy数组的列?
解决方法
错误原因
Y是Python列表,而非numpy数组,列表仅支持整数或切片索引,不支持numpy的多维元组索引([:,0]这种形式),因此会抛出TypeError: list indices must be integers or slices, not tuple。
遍历所有数组的所有列
要打印Y中所有数组的每一列,需先遍历列表中的每个numpy数组,再对每个数组提取列:
方法1:循环列索引提取
import numpy as np Y = [np.array([[1, 4, 7], [2, 5, 8]]), np.array([[10, 14, 18], [11, 15, 19], [12, 16, 20], [13, 17, 21]]), np.array([[22, 26, 31], [24, 28, 33], [26, 30, 35]])] # 遍历列表中的每个numpy数组 for idx, arr in enumerate(Y): print(f"第{idx+1}个数组的所有列:") # 获取数组的列数 col_count = arr.shape[1] # 遍历每一列索引 for col_idx in range(col_count): # 提取列并转为二维列向量(匹配示例格式) column = arr[:, col_idx].reshape(-1, 1) print(column) print("-"*10)
方法2:用numpy.split按列拆分
for idx, arr in enumerate(Y): print(f"第{idx+1}个数组的所有列:") # 按列拆分为单个列数组 columns = np.split(arr, arr.shape[1], axis=1) for col in columns: print(col) print("-"*10)
输出示例(第一个数组)
第1个数组的所有列: [[1] [2]] ---------- [[4] [5]] ---------- [[7] [8]] ----------
内容的提问来源于stack exchange,提问作者Amelia
相关产品推荐
相关产品推荐

