首页 > 解决方案 > 用一行在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解决方案?

多谢你们

标签: pythonlistnumpy

解决方案


从...开始:

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]])

推荐阅读