使用2d嵌套字典中的if / else语句进行列表理解循环

时间:2018-06-28 07:18:10

标签: python-3.x for-loop if-statement list-comprehension

下面的代码片段可以正常工作,并且可以产生我想要的东西,但是我需要一些关于如何使Pythonic更加线条化的指针

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

完整代码

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}.") 

所以我尝试使if avail[employee, day, shift].varValue==0 for shift in Shift_pattern_Master:成为通用条件,并且一直说for是无效语法。

我想我缺少了一些东西,但是我不知道是什么。感谢您的任何提前帮助。

1 个答案:

答案 0 :(得分:2)

怎么样:

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

另一种选择是重新包装条件:

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