繁体   English   中英

如何在2d嵌套的python中对纸浆进行循环理解

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

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

我有2种转换模式:“ Shift_Pattern_1”和“ Shift_Pattern_Master”

员工是一个列表,里面有名字。

 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. 有没有更好的方法来使用更多pythonic?

    对于天中的天:如果Week1 [day] == 2:对于员工中的员工:prob + = pulp.lpSum(可用[员工,天,班次]
    Shift_pattern_1)==请求[员工] [天]否则:
    概率+ = pulp.lpSum(在Shift_pattern_Master中可用[班次[员工,天,班]] ==请求[员工] [天]

提前致谢。

如果唯一的一天是星期三,则要执行以下操作:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM