oneliner python中的多个ifs和elif

时间:2017-04-12 06:54:45

标签: python

我有这段代码:

a = 0
if 0 < b <= 100:
    a = 10
elif 100 < b <= 1000:
    a = 40
elif 1000 < b <= 5000:
    a = 90
elif 5000 < b <= 10000:
    a = 180
elif 10000 < b <= 20000:
    a = 350
elif 20000 < b <= 100000:
    a = 700
elif 100000 < b <= 300000:
    a = 1400
elif 300000 < b:
    a = 3300
print a

有没有办法以某种方式减少它,也许可以制作一行?

1 个答案:

答案 0 :(得分:2)

试试这个:

a=10
a= {0 < b <= 100: 10, 100< b <= 1000: 40, 1000 < b <= 5000: 90, 5000 < b <= 10000: 180, 10000 < b <= 20000:350, 20000 < b <= 100000: 700, 100000 < b <= 300000:1400, 300000 < b:3300}.get(True, a)