Multiple ifs and elifs in oneliner python
本问题已经有最佳答案,请猛点这里访问。
我有这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 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) |