用单行获取python中数组的元素

时间:2019-05-13 23:13:06

标签: python list numpy

我需要使用这个漂亮的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解决方案?

谢谢大家

3 个答案:

答案 0 :(得分:4)

更好的Pythonic解决方案

>>> train_predicteds[:,0,0]
array([0.1, 0.3])

答案 1 :(得分:4)

开始于:

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

前两个尺寸可以通过变形合并:

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

答案 2 :(得分:2)

您可以通过简单的循环理解来做到这一点:

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

result = [list(train_predicteds[:, i, j]) for i in range(3) for j in range(3)]

输出:

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

更新:

感谢Reedinationer指出

或者,如果您希望使用更通用的形式:

result = [list(train_predicteds[:, i, j]) for i in range(len(train_predicteds[0])) for j in range(len(train_predicteds[0, 0]))]