处理多种情况的最佳方法

2024-09-25 04:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试创建一个变量,可以在其中添加多个条件,以便在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):
...

最好的方法是什么?也许有一种不用绳子的方法


Tags: orand方法falseformatdef语句条件
2条回答

您可以使用一系列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))

相关问题 更多 >