簡體   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