【问题标题】:How to match indexes from one list to another list and store values?如何将一个列表中的索引匹配到另一个列表并存储值?
【发布时间】:2020-06-06 10:57:36
【问题描述】:

我的项目需要帮助。

事情是这样的:

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)]]

问题是:prod3 索引。如果我要执行上面的代码,max_prodindexes 1 and 2,而当我尝试打印它的dur_same 时,我得到的[5, 3] 与它在产品中的假定索引不匹配。如何确保/匹配dur_same 的索引与其在prod 中的索引,然后将0 用于其他索引/es?

我在该部分的预期输出应该是:

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之间随机选择,然后选择它对应的activity呢?

任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: python python-3.x indexing insert


    【解决方案1】:

    您可以稍微修改列表推导来实现这一点。

    这就是你现在的做法:

    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]
    

    【讨论】:

    • 我尝试编写代码,它运行良好。只是一个后续问题,如果您不介意,我如何调用/选择与 dur_same 中的最大值具有相同索引的活动?到目前为止,该部分的代码如下所示:select_act = [d for a, d in zip(dur, activity) if a == max(dur_same)]。但这会将 max(dur_same) 与 dur 匹配并获取活动。事情是 dur = [5, 5, 3] 所以代码需要两个值 5。
    猜你喜欢
    • 1970-01-01
    • 2022-07-31
    • 2020-10-08
    • 2014-02-12
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2012-09-19
    相关资源
    最近更新 更多