python - 用一行在python中获取数组的元素
问题描述
我需要使用这个漂亮的 np 数组
import numpy as np
train_predicteds = np.asarray([
[[0.1, 0.2, 0.3], [0.5, 0.6, 0.7], [0.7, 0.8, 0.9]],
[[0.3, 0.1, 0.4], [0.4, 0.5, 0.6], [0.5, 0.6, 0.1]]])
现在我想以这种方式获取元素:
[[0.1, 0.3], [0.2, 0.1], [0.3, 0.4],
[0.5, 0.4], [0.6, 0.5], [0.7, 0.6],
[0.7, 0.5], [0.8, 0.6], [0.9, 0.1]]
我发现的某种解决方案是使用这两行:
aux = [item[0] for item in train_predicteds]
x = [item[0] for item in aux]
这产生了我 x 等于
[0.10000000000000001, 0.30000000000000001]
但是我不能将这两行合并为一条,可以吗?还是有更好的pythonic解决方案?
多谢你们
解决方案
从...开始:
In [17]: arr = np.asarray([
...: [[0.1, 0.2, 0.3], [0.5, 0.6, 0.7], [0.7, 0.8, 0.9]],
...: [[0.3, 0.1, 0.4], [0.4, 0.5, 0.6], [0.5, 0.6, 0.1]]])
In [18]: arr
Out[18]:
array([[[0.1, 0.2, 0.3],
[0.5, 0.6, 0.7],
[0.7, 0.8, 0.9]],
[[0.3, 0.1, 0.4],
[0.4, 0.5, 0.6],
[0.5, 0.6, 0.1]]])
In [19]: arr.shape
Out[19]: (2, 3, 3)
在尝试了几个转置命令后,我得到了:
In [26]: arr.transpose(1,2,0) # shape (3,3,2) moves 1st dim to end
Out[26]:
array([[[0.1, 0.3],
[0.2, 0.1],
[0.3, 0.4]],
[[0.5, 0.4],
[0.6, 0.5],
[0.7, 0.6]],
[[0.7, 0.5],
[0.8, 0.6],
[0.9, 0.1]]])
前两个维度可以用 reshape 合并:
In [27]: arr.transpose(1,2,0).reshape(9,2)
Out[27]:
array([[0.1, 0.3],
[0.2, 0.1],
[0.3, 0.4],
[0.5, 0.4],
[0.6, 0.5],
[0.7, 0.6],
[0.7, 0.5],
[0.8, 0.6],
[0.9, 0.1]])
推荐阅读
- image - Flutter:将 Base64 字符串转换为图像(类型文件变量)
- javascript - 为高阶组件传递两次道具?
- python - 子列表切片的条件、逐项添加
- ios - 当用户单击通知时不弹出本地通知时执行功能
- vue.js - Tabview 未在 nativescript-vue 的第一个选项卡中显示数据
- javascript - 过滤器不适用于更改输入文本:ReactJS
- android - Android Vulkan 链接器命令失败
- ios - 如何完全打开蓝牙强制或如何在我的 ios 应用程序中请求打开蓝牙的权限
- javascript - javascript 动态 HTML 表格行导致问题
- c++ - unordered_set 创建用于在向量中查找整数对