gpt4 book ai didi

python - python 中的复杂 if-elif

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:58 26 4
gpt4 key购买 nike

我正在尝试在 python 中创建一个复杂的 if else 语句。这些语句应该检查两个变量。示例代码:

    if value1 == 0.1 and value2 > 2.05:
value1 = value1 + 0.1
return value1
elif value1 == 0.2 and value2 > 1.85:
value1 = value1 + 0.1
elif value1 == 0.3 and value2 > 1.95:
value1 = value1 + 0.1
elif value1 == 0.4 and value2 > 2.05:
value1 = value1 + 0.1
...
if value1 == 0.1 and value2 < 1.75:
return value1
elif value1 == 0.2 and value2 < 1.85:
value1 = value1 - 0.1
elif value1 == 0.3 and value2 < 1.95:
value1 = value1 - 0.1
elif value1 == 0.4 and value2 < 2.05:
value1 = value1 - 0.1
....

总的来说,对于 0.1 - 1 之间的每个 value1,我都有一个 if 或 elif。每次 value2 都是不同的值。我想要做的是检查 value2 是否小于一个值以减少 value1 = value -1。在不添加许多 if -elif 语句的情况下,哪种方法最聪明?

最佳答案

如果没有模式或者它太复杂以至于不能轻易地用循环构造它那么我会做这样的事情:

eq_gt_pairs = ((0.1, 2.05), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...

eq_lt_pairs = ((0.1, 1.75), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...

for pair in eq_gt_pairs:
if value1 == pair[0] and value2 > pair[1]:
return value1 + 0.1

for pair in eq_lt_pairs:
if value1 == pair[0] and value2 < pair[1]:
return value1 - 0.1

关于python - python 中的复杂 if-elif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com