【发布时间】:2019-11-26 15:15:49
【问题描述】:
我理解 Python 的核心在于效率。 我将如何编写下面的代码以使其更具 Pythonic?
我想过使用字典,但由于elif 语句的条件是范围,我认为这是不可能的。
threshold_scale
if pop in range(threshold_scale[0], threshold_scale[1]):
color = '#ff0000'
elif pop in range(threshold_scale[1], threshold_scale[2]):
color = '#f6ff00'
elif pop in range(threshold_scale[2], threshold_scale[3]):
color = '#00ff08'
elif pop in range(threshold_scale[3], threshold_scale[4]):
color = '#0d00ff'
elif pop in range(threshold_scale[4], threshold_scale[5]+1):
color = '#ff00f7'
输出
[1960, 648065, 1294170, 1940275, 2586380, 3232486]
【问题讨论】:
-
“Python 就是为了效率” ??从何时起?您发布的代码有什么问题?
-
效率方面,这段代码没有任何问题。
in range(...)是 O(1) 检查,elif确保只进行最少数量的检查。 -
而且,FWIW,
range对象是可散列的,因此它们可以用作字典键 -
我认为字典在这里是个不错的选择。
-
我不知道范围可以在字典中使用,因为我找到的所有字典示例都使用字符串对象。谢谢你告诉我。
标签: python python-3.x dictionary if-statement