Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 高级切片:给定索引列表,从numpy数组中选择不同的元素_Python_Python 3.x_Numpy_Slice - Fatal编程技术网

Python 高级切片:给定索引列表,从numpy数组中选择不同的元素

Python 高级切片:给定索引列表,从numpy数组中选择不同的元素,python,python-3.x,numpy,slice,Python,Python 3.x,Numpy,Slice,我正在实现一个决策算法。在daily\u choices数组中,每天有两种水果可供选择,例如: daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']]) 现在,我有一张清单,上面列出了我每天要选择的水果: decision = [0,1,0] 我知道一些基本的切片,例如daily\u choices[:,0],它意味着将第一列切片,而daily\u choice

我正在实现一个决策算法。在
daily\u choices
数组中,每天有两种水果可供选择,例如:

daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']])
现在,我有一张清单,上面列出了我每天要选择的水果:

decision = [0,1,0] 
我知道一些基本的切片,例如
daily\u choices[:,0]
,它意味着将第一列切片,而
daily\u choices[:,1]
意味着将第二列切片

我想知道是否有任何方法可以通过执行以下操作来分割第一行中的第一列、第二行中的第二列、第三行中的第一列

预期结果 然而,它并没有给我想要的结果

我知道通过使用
zip
和for
loop

daily_decision
daily_decision = []
for choices, index in zip(daily_choices, decision):
    daily_decision.append(choices[index])
daily_decision
但我想知道是否有可能在一行中完成。

使用列表理解 [‘苹果’、‘橘子’、‘西瓜’]

使用numpy 这也可以通过以下方法解决:

[‘苹果’、‘橘子’、‘西瓜’]


纯粹使用
numpy

import numpy as np

daily_choices = np.array([['apple', 'orange'],['strawberry', 'orange'],['watermelon', 'apple']])
decision = np.array([0, 1, 0])

n_fruits = 2

fruit_range = np.reshape(np.arange(n_fruits), (-1, n_fruits))
indices = np.reshape(decision, (len(decision), 1)) == fruit_range

daily_choices[indices]
输出:

array(['apple', 'orange', 'watermelon'], dtype='<U10')

array(['apple'、'orange'、'西瓜'],dtype='use
daily\u decision=[choices[index]for choices,index in zip(daily\u choices,decision)]
import numpy as np
daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']])
decisions = [0, 1, 0]

daily_decision = daily_choices[range(len(daily_choices)), decisions]
print(daily_decision)
import numpy as np

daily_choices = np.array([['apple', 'orange'],['strawberry', 'orange'],['watermelon', 'apple']])
decision = np.array([0, 1, 0])

n_fruits = 2

fruit_range = np.reshape(np.arange(n_fruits), (-1, n_fruits))
indices = np.reshape(decision, (len(decision), 1)) == fruit_range

daily_choices[indices]
array(['apple', 'orange', 'watermelon'], dtype='<U10')