处理多种情况的最佳方式

Best way to handle multiple conditions

我尝试制作一个变量,我可以在其中添加多个条件以在 while 语句中使用它

conditionData = "False"

def conditionConstructor(xStart, xEnd, yStart, yEnd, conditionData):
    conditionData += " or (({} < x < {}) and ({} < y < {}))".format(xStart, xEnd, yStart, yEnd)
    return conditionData

conditionConstructor(1, 2, 3, 4, conditionData)
conditionConstructor(3, 4, 1, 2, conditionData)

while(conditionData):
...

最好的方法是什么?也许有一种不用字符串的方法?

您可以使用一系列 lambda 来获得您想要的。

字符串从来都不是这样。

def conditionConstructor(xStart, xEnd, yStart, yEnd, condition = lambda x,y:False):
    return lambda x,y: condition(x,y) or (xStart < x < xEnd) and (yStart < y < yEnd)


c1 = conditionConstructor(1, 2, 3, 4)
c2 = conditionConstructor(3, 4, 1, 2, c1)

x = 1.1
y = 3.3
while c2(x,y):
    print(x,y)
    x += 0.3
    y += 0.3

输出:

1.1 3.3
1.4000000000000001 3.5999999999999996
1.7000000000000002 3.8999999999999995

要将字符串用作代码,您需要谨慎使用 eval 函数,因为如果您依赖于用户的输入,它不是一个安全的函数。 请注意,f 弦是改进的 format.

def conditionConstructor(xStart, xEnd, yStart, yEnd, conditionData='False'):
    return f'{conditionData} or (({xStart} < x < {xEnd}) and ({yStart} < y < {yEnd}))'


def main():
    x = 2
    y = 4
    res = conditionConstructor(1, 3, 3, 5)
    res = conditionConstructor(3, 4, 1, 2, res)

    while eval(res):
        ...


if __name__ == '__main__':
    main()

打印第一个 res 将显示:
False or ((1 < x < 3) and (3 < y < 5)).

打印第二个 res 将显示:
False or ((1 < x < 3) and (3 < y < 5)) or ((3 < x < 4) and (1 < y < 2))