Python 如何将索引从一个列表匹配到另一个列表并存储值?

Python 如何将索引从一个列表匹配到另一个列表并存储值?,python,python-3.x,indexing,insert,Python,Python 3.x,Indexing,Insert,我的项目需要帮助 事情是这样的: prod = [0, 5, 5] dur = [5, 5, 3] activity = [2, 3, 4] max_r = 6 现在,我要做的是选择一个符合以下条件的活动: 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

我的项目需要帮助

事情是这样的:

prod = [0, 5, 5]
dur = [5, 5, 3]
activity = [2, 3, 4]
max_r = 6
现在,我要做的是选择一个符合以下条件的活动:

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)]]
这样,就更容易调用其相应的活动。因为我所要做的就是将
dur\u same
中的最高持续时间与
dur
匹配,并在
dur
中获得匹配的索引。然后,使用此索引获取活动

编辑: 如果对于dur具有相同最高值的实例,让我们假设
dur\u same=[0,5,5]
。我怎么能在两个5s中随机选择,然后选择相应的活动


任何帮助都将不胜感激!谢谢大家!

您可以稍微修改列表以实现此目的

这就是您现在的做法:

In [1]: [d for a, d in zip(prod, dur) if a == max_prod]                                                                
Out[1]: [5, 3]
如果不是,请将此更改为单行。如果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]

我试着编写代码,效果非常好。如果您不介意的话,我只是想问一个后续问题,我如何调用/选择索引与dur_same中的max相同的活动?到目前为止,我对该部分的代码如下所示:如果a==max(dur\u same),则选择[d代表a,d在zip(dur,activity)中。但这会将max(dur_same)与dur匹配,并获得活动。事情是dur=[5,5,3],因此代码调用了两个值5。
In [2]: [d if a == max_prod else 0 for a, d in zip(prod, dur)]                                                         
Out[2]: [0, 5, 3]