首页 > 解决方案 > 使用二维嵌套字典中的 if/else 语句进行列表理解循环

问题描述

下面的代码片段有效,它产生了我想要的东西,但是我需要一些关于如何使用该行更加 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是无效的语法。

我想我错过了什么,但我不知道是什么。感谢您提前提供任何帮助。

标签: python-3.xfor-loopif-statementlist-comprehension

解决方案


怎么样:

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
):

推荐阅读