简体   繁体   中英

list comprehension looping with if/else statement from 2d nested dictionary

The following snippet works and it produces exactly what I want, however I need some pointers on how to be more Pythonic with the line

if avail[employee, day, "Morning"].varValue==0 and    
    avail[employee, day, "Mid"].varValue==0 and 
    avail[employee, day, "Night"].varValue==0:

Full code

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

    for employee in Employees:
        for day in Days:
            if avail[employee, day, "Morning"].varValue==0 and    
                avail[employee, day, "Mid"].varValue==0 and 
                avail[employee, day, "Night"].varValue==0:
                    print (f"{employee} on {day} is off.")
            else:
                for shift in Shift_pattern_Master:
                    if avail[employee, day, shift].varValue==1:
                        print (f"{employee} on {day} works in {shift}.") 

so I tried if avail[employee, day, shift].varValue==0 for shift in Shift_pattern_Master: to make it a generic condition and it keeps saying for is INVALID SYNTAX.

I think I am missing something, but I don't know what. Thanks for any help in advance.

How about:

if all(avail[employee, day, time].varValue==0 for time in ["Morning", "Mid", "Night"]):

Another option would be just to rewrap the condition:

if (
    avail[employee, day, "Morning"].varValue==0
    and avail[employee, day, "Mid"].varValue==0
    and avail[employee, day, "Night"].varValue==0
):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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