2 回答
TA贡献1864条经验 获得超2个赞
使用列表理解
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)
['苹果','橙色','西瓜']
使用 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)
['苹果','橙色','西瓜']
TA贡献1824条经验 获得超8个赞
纯粹使用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')
添加回答
举报