我正在实现决策制定算法。在daily_choices
数组中,每天有两种水果可供选择,例如:
daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']])
现在我有一个 list ,其中包含我每天要选择的水果:
decision = [0,1,0]
我知道一些基本的切片,比如daily_choices[:,0]
,意思是把第一列切片出来,daily_choices[:,1]
意思是切片第二列。
我想知道是否有通过执行以下操作来对第一行的第一列、第二行的第二列、第三行的第一列进行切片
预期结果
Input => daily_choices[:,[0,1,0]]
Output => ['apple', 'orange', 'watermelon']
然而,它并没有给我想要的结果
我知道我可以通过使用 zip
和 for loop
daily_decision
daily_decision = []
for choices, index in zip(daily_choices, decision):
daily_decision.append(choices[index])
daily_decision
但我想知道是否可以一行完成。
最佳答案
使用列表理解
choices = [['apple', 'orange'], ['strawberry', 'orange'], ['watermelon', 'apple']]
decisions = [0, 1, 0]
daily_decisions = [day[decision] for day, decision in zip(choices, decision)]
print(daily_decisions)
['apple', 'orange', 'watermelon']
使用 numpy
这也可以通过 NumPys Integer Array Indexing 来解决。 :
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)
['apple', 'orange', 'watermelon']
关于python - 高级切片 : Given a list of index, 从 numpy 数组中选取不同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062676/