如何在 2d 中成为 pythonic 嵌套循环理解纸浆

how to be pythonic in a 2d nested for loop comprehension for pulp

我无法克服我程序中的这个障碍。我想将这个重复的代码减少到一个更简单的代码。简而言之,这些是对纸浆的限制。

我有 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 个约束。我知道问题是 "if Week1[day]==2" 因为缺少一些约束。

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

    天数: 如果第 1 周[天]==2: 对于员工中的员工: prob += pulp.lpSum(avail[employee, day, shift] for shift in
    Shift_pattern_1)==请求[员工][天] 否则:
    prob += pulp.lpSum(avail[employee, day, shift] for shift in Shift_pattern_Master)==requests[employee][day]

提前致谢。

如果唯一的一天是星期三你想做的事:

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]