[英]How to extract values from list of dictionary that match the keys in another list
[英]How to match indexes from one list to another list and store values?
我的项目需要帮助。
这是怎么回事:
prod = [0, 5, 5]
dur = [5, 5, 3]
activity = [2, 3, 4]
max_r = 6
现在,我要做的是 select 遵循以下条件的活动:
max_prod = max(prod)
if max_prod <= max_r:
# if yes and appears more than once, check dur, the activity with the highest duration will be put to select_act
if prod.count(max_prod) > 1:
# know the indexes of the values that appears more than once in prod
idx = list_duplicates_of(prod, max_prod)
# then get duration of these values
dur_same = [d for a, d in zip(prod, dur) if a == max_prod]
print(dur_same)
#select the activity that has the highest duration
#get dur of that selected activity
# if yes and appears only once, get activity and put in select_act
else:
select_act = [activity[prod.index(max_prod)]]
dur_select_act = [dur[prod.index(max_prod)]]
问题是: prod
有3
索引。 如果我要执行上面的代码, max_prod
的indexes 1 and 2
,而当我尝试打印它的dur_same
时,我得到的[5, 3]
与它在 prod 中的假定索引不匹配。 我如何确保/匹配dur_same
的索引与其在prod
中的索引,并为其他索引/es 设置0
?
我在该部分的预期 output 应该是:
prod = [0, 5, 5]
dur_same = [0, 5, 3] #instead of just [5, 3] from the code above
这样,更容易调用其对应的活动。 因为我所要做的就是将dur_same
中的最高持续时间与dur
匹配,并在dur
中获取匹配的索引。 然后,使用此索引获取活动。
编辑:如果对于 dur 具有相同最大值的实例,假设dur_same = [0, 5, 5]
。 我怎么能在两个5s之间随机选择,然后select对应的活动呢?
任何帮助,将不胜感激! 谢谢!
您可以稍微修改列表推导来实现这一点。
这就是你现在的做法:
In [1]: [d for a, d in zip(prod, dur) if a == max_prod]
Out[1]: [5, 3]
您将其更改为单行 if-else。 如果 a == max_prod,它会将 d 添加到列表中,否则它将添加 0。
In [2]: [d if a == max_prod else 0 for a, d in zip(prod, dur)]
Out[2]: [0, 5, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.