#Python 工匠:使用数字与字符串的技巧学习笔记
#https://github.com/piglei/one-python-craftsman/blob/master/zh_CN/3-tips-on-numbers-and-strings.md
:使用 enum 枚举类型改善代码
#避免如下代码
def mark_trip_as_featured(trip):
"""将某个旅程添加到推荐栏目
"""
if trip.source == 11:
do_some_thing(trip)
elif trip.source == 12:
do_some_other_thing(trip)
... ...
return
#提倡如下代码
from enum import IntEnum
class TripSource(IntEnum):
FROM_WEBSITE = 11
FROM_IOS_CLIENT = 12
def mark_trip_as_featured(trip):
if trip.source == TripSource.FROM_WEBSITE:
do_some_thing(trip)
elif trip.source == TripSource.FROM_IOS_CLIENT:
do_some_other_thing(trip)
... ...
return
:不必预计算字面量表达式
#避免如下代码
def f1(delta_seconds):
# 如果时间已经过去了超过 11 天,不做任何事
if delta_seconds > 950400:
return
...
#提倡如下代码
def f1(delta_seconds):
if delta_seconds > 11 * 24 * 3600:
return
实用技巧
1.布尔值其实也是“数字”
["Python", "Javascript"][2 > 1]
'Javascript'
[2>1]为True,True即1
["Python", "Javascript"][1]
2.改善超长字符串的可读性
使用括号将长字符串包起来,然后就可以随意折行了:
def main():
logger.info(("There is something really bad happened during the process. "
"Please contact your administrator."))
可以用标准库 textwrap 来解决整段代码的缩进视觉效果
from textwrap import dedent
def main():
if user.is_active:
# dedent 将会缩进掉整段文字最左边的空字符串
message = dedent("""\
Welcome, today's movie list:
- Jaw (1975)
- The Shining (1980)
- Saw (2004)""")
3.float("inf") 和 float("-inf") 它们俩分别对应着数学世界里的正负无穷大。当它们和任意数值进行比较时,满足这样的规律:float("-inf") < 任意数值 < float("inf")。
因为它们有着这样的特点,我们可以在某些场景用上它们:
# A. 根据年龄升序排序,没有提供年龄放在最后边
>>> users = {
"tom": 19, "jenny": 13, "jack": None, "andrew": 43}
>>> sorted(users.keys(), key=lambda user: users.get(user) or float('inf'))
['jenny', 'tom', 'andrew', 'jack']
# B. 作为循环初始值,简化第一次判断逻辑
>>> max_num = float('-inf')
>>> # 找到列表中最大的数字
>>> for i in [23, 71, 3, 21, 8]:
...: if i > max_num:
...: max_num = i
...:
>>> max_num
71