Python 速查表

本文介绍 Python 编程中的常见问题的处理方法

类型/转换

1
2
3
4
5
6
# 赋空值
v = None

# 数字 --> 字符串
n = 2
s = str(n)

数字处理

1
2
3
4
5
6
7
8
# 四舍五入
round(1.126, 2) # output: 1.3
round(1.123, 2) # output: 1.2

# Decimal 转换成 float
from decimal import Decimal
d = Decimal(1.2)
f = float(d)

字符串

1
2
3
4
5
6
7
8
9
10
11
# 字符串连接
'abc'+'def' # output: 'abcdef'
'\n'.join(['1st line', '2nd line']) # output: ' 1st line\n2nd line'
'\n'.join('12') # output: '1\n2'

# 判断字符串包含子串
'bc' in 'abcd' # output: True

# 获取子字符串
s = "Hello world"
s[0:5] # output 'Hello'

日期/时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from datetime import datetime

from dateutil.relativedelta import relativedelta
import pytz

# 设置时区
pytz.timezone('Asia/Shanghai')

# 构造时间
d = datetime(2017,10,1)

# 从日期字符串创建日期对象
d = datetime.strptime('2017-08-24 00:00:00', '%Y-%m-%d %H:%M:%S')

# 设置日期/时间对象的时间部分为 00:00:00
d_midnight = d.replace(hour=0, minute=0, second=0, microsecond=0)

# 获取某日期的月首日
firstd = d.replace(day=1)

# 获取某日期的月末日期
lastd = (d + relativedelta(months=+1)).replace(day=1) + relativedelta(days=-1)

# 将日期对象格式化成日期字符串
format_date_str = d.strftime('%Y-%m-%d') # 格式化成形如 2017-10-01 的形式

集合处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 定义列表
[1, 2, 3]
['how', 'are', 'you']

# 列表中添加元素
c = [1, 2, 3]
c.append(5) # c is [1,2,3,5]

# 获取子列表
c = [1, 2, 3, 5, 7, 8]
c[3:5] # output [5,7]

# 列表连接
a = [1,2]
b = [3,4]
c = a + b # output: [1,2,3,4]
c += a # output: [1,2,3,4,1,2]


# 定义字典
dic = {'first': 123, 'second': 567}

# 找出字典中最小/最小值的索引
dic = {'first': 123, 'second': 567}
min(dic, key=dic.get) # output: first
max(dic, key=dic.get) # output: second

# 字典元素按值排序
d = {'a': 3, 'b': 1, 'c': 2}
## 方法1
sorted([(el, d[el]) for el in d], key=lambda x: x[1]) # output: [('b', 1), ('c', 2), ('a', 3)]
## 方法2
sorted([el for el in d.items()], key=lambda x: x[1]) # output: [('b', 1), ('c', 2), ('a', 3)]
## 方法3
import operator
sorted(d.items(), key=operator.itemgetter(1)) # output: [('b', 1), ('c', 2), ('a', 3)]

# 集合元素求和
c = [{'v':1}, {'v':2}, {'v':3}]
sum_v = sum(el['v'] for el in c) # output: 6

# 集合映射(map操作)
c = [{'v':1}, {'v':2}, {'v':3}]
new_c = [{'m':el['v'] * 2} for el in c] # output: [{'m': 2}, {'m': 4}, {'m': 6}]
new_c = [{'m':el['v'] * 2} for el in c if el['v'] > 1] # output: [{'m': 4}, {'m': 6}]

# 集合排序
c = [{'v':2}, {'v':3}, {'v':1}]
sorted(c, key=lambda x: x['v']) # output: 正序 [{'v':1}, {'v':2}, {'v':3}]
sorted(c, key=lambda x: x['v'], reverse=True) # output: 倒序 [{'v':3}, {'v':2}, {'v':1}]

# 集合过滤
c = [{'v':2}, {'v':3}, {'v':1}, {'v':9}]
list(filter(lambda x: 1 <= x['v'] < 3 and x['v'] == 9, c)) # output: [{'v': 2}, {'v': 1}, {'v': 9}]

磁盘路径处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 获取当前工作目录
import os

os.path.join(os.getcwd(), '')

# 获取当前执行的python文件名,当在 python shell 中执行时无效
__file__

# 获取当前目录, 其中:在 python shell 中执行时用 else 后的代码
import os
DIR = os.path.dirname(__file__) if '__file__' in vars() else os.path.join(os.getcwd(), '')

# 获取某文件/目录的父目录
import os

os.path.dirname(filename)

流程控制

1
2
3
4
5
6
7
# 按自然数循环
for i in range(5):
print(i)

# C 语言问号表达式在 Python 中的等价物
a = 20
r = a / 10 if a else 0