【问题标题】:How to use lookup or hashmap instead of if else?如何使用 lookup 或 hashmap 而不是 if else?
【发布时间】:2022-11-25 11:57:08
【问题描述】:
if Profit<=10000:
    print('Profit Rating is 1')
elif 10001<=Profit<=20000:
    print('Profit Rating is 2')
elif 20001<=Profit<=30000:
    print('Profit Rating is 3')
elif 30001<=Profit<=40000:
    print('Profit Rating is 4')
elif 40001<=Profit<=50000:
    print('Profit Rating is 5')
elif 50001<=Profit<=60000:
    print('Profit Rating is 6')
elif 60001<=Profit<=70000:
    print('Profit Rating is 7')
elif 70001<=Profit<=80000:
    print('Profit Rating is 8')
elif 80001<=Profit<=90000:
    print('Profit Rating is 9')
else:
    print('Profit Rating is 10')

如果还有,请帮我删除上面的内容。 我尝试使用查找和映射,但它不起作用。

我想摆脱 if、elif 和 else。

【问题讨论】:

标签: python-3.x


【解决方案1】:

使用简单的数学:

import math

if Profit > 90000:
    profit_rating = 10
else:
    profit_rating = math.ceil(Profit / 10000)

print(f"Profit Rating is {profit_rating}")

它会将您的数字除以 10,000,然后四舍五入。这基本上就是您在原始 if/else 解决方案中尝试(手动)执行的操作。

【讨论】:

  • 你可以解释吗?我没明白
  • fot 150000 它返回 15 我想要 10?
  • 它会将您的数字除以 10,000,然后四舍五入。这基本上就是您在原始 if/else 解决方案中尝试(手动)执行的操作。
  • 它现在为任何超过 90K 的东西返回 10
  • 收到了。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 2018-09-26
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 2020-03-23
相关资源
最近更新 更多