【问题标题】:how to be pythonic in a 2d nested for loop comprehension for pulp如何在 2d 嵌套 for 循环理解中成为 Pythonic
【发布时间】:2018-12-03 18:05:18
【问题描述】:

我无法克服我的程序中的这个问题。我想将这个重复的代码简化为更简单的代码。简而言之,这些是纸浆的限制条件。

我有 2 个班次模式:“Shift_Pattern_1”和“Shift_Pattern_Master”

Employees 是一个包含名字的列表。

 Days:["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",    
 "Saturday", "Sunday"]

Shift_pattern_Master = ["Morning", "Mid", "Night"]
Shift_pattern_1 = ["Morning", "Night"]

Week1={"Monday":2, "Tuesday":2, "Wednesday":3, "Thursday":2, "Friday":2,    
"Saturday":3, "Sunday":2} # number a people needed a to day work.

for day in Days[0:2]: # Monday and Tuesday only
    for employee in Employees:
        prob += pulp.lpSum(avail[employee, day, shift] for shift in      
Shift_pattern_1)==requests[employee][day]

for day in Days[2:3]: #wednesday
    for employee in Employees:
        prob += pulp.lpSum(avail[employee, day, shift] for shift in     
 Shift_pattern_Master)==requests[employee][day]

 ....more code to finish the week.........

当我从上面完成整个代码时,我得到了 35 个约束。

我的尝试是使用 if 和 else 来缩短代码,但我只得到 30 个约束。我知道问题是“如果 Week1[day]==2”,因为缺少一些约束。

  1. 我不知道该 if 语句应该放在哪里,或者
  2. 有没有更好的方法来更 Python 化?

    以天为单位: 如果 Week1[day]==2: 对于员工中的员工: prob += pinch.lpSum(avail[employee, day, shift] for shift in
    Shift_pattern_1)==requests[员工][天] 其他:
    prob += pinch.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]

提前致谢。

【问题讨论】:

    标签: python-3.x for-loop dictionary-comprehension pulp


    【解决方案1】:

    如果独特的一天是你想要做的星期三:

    for day in Days: 
       if day=="Wednesday": 
          for employee in Employees: 
              prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_1)==requests[employee][day] 
       else:
          for employee in Employees: 
              prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]
    

    但是,我认为您实际上想要上述条件,因此您只需要包含员工循环

    for day in Days: 
       if Week1[day]==2: 
          for employee in Employees: 
              prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_1)==requests[employee][day] 
       else:
          for employee in Employees: 
              prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]
    

    【讨论】:

    • 嗨斯图尔特,再次感谢。有效。我不知道我需要那个。这些 2d 嵌套字典对我来说非常复杂。现在我可以继续下一部分了。
    猜你喜欢
    • 2020-06-08
    • 2017-08-20
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2018-11-27
    • 2011-04-07
    相关资源
    最近更新 更多