【问题标题】:list comprehension looping with if/else statement from 2d nested dictionary使用 2d 嵌套字典中的 if/else 语句进行列表理解循环
【发布时间】:2018-06-28 07:18:10
【问题描述】:

下面的 sn-p 可以工作,它产生的正是我想要的,但是我需要一些关于如何使用该行更加 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.x for-loop if-statement list-comprehension


    【解决方案1】:

    怎么样:

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

    【讨论】:

    • 我建议的一个小改动 - 将 X==0 替换为 not X
    • 可能是个好主意(然后你也可以做not any(ava.....varValue for ti....),但不是严格等价的。
    • 谢谢@L3viathan。它工作得很好。这就是我所缺少的。我还是个初学者,我今天肯定学到了一些东西。
    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2018-09-08
    • 2012-03-12
    • 2020-10-13
    相关资源
    最近更新 更多