Python常见技巧

说明:用来记录python当中遇到的一些小问题和技巧

[TOC]


代码规范

  1. 首先写注释
  2. 所有运算符前后加空格,逗号后加空格
  3. 代码块之间以两行空行分隔,代码块内部以单行空格分隔
  4. 其它

常见技巧

1. 关于print函数

print函数的说明如下:

1
2
3
4
5
6
7
8
9
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

因此可以控制打印输出时候的连接符以及结尾的控制。

对于后续的两个参数的说明:

  • file:输出print到哪个文件,例如可以输出到一个txt中:

    1
    2
    3
    f = open(r'a.txt', 'w')
    print("Hello world!", file = f)
    f.close()

    原始的 sys.stdout 指向控制台,你也可以直接将其规定指向一个文件,但是后续使用print输出的内容,都会写入到该文件中。(因此最好先保存初始的sys.stdout),以下两行代码在事实上是等效的:

    1
    2
    sys.stdout.write('hello'+'\n')
    print('hello')
  • flush:英文是“冲走,冲掉”的意思,表示是否对输出立即刷新。默认情况下,print到f中的内容先从到内存中,当文件对象关闭时才把内容输出到 a.txt 中,当flush=True时它会立即把内容刷新存到 a.txt 中。因此如果想马上看到结果,需要设置flush为True

2. 双除号

  • 双除号 “//” 表示向下取整
  • 注意精度保持一致

3. 生成随机数

python有两种方式来生成随机数

  • 一是使用自带的random包
  • 二是借助numpy包

参考资料:

4. 打印二维表格

问题描述:

使用print打印二维表格(存储了一些整数),并且希望打印格式为每个数字占据3位宽度

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
testData = np.random.randint(30, size = (10, 9))

# 第一种方式(有时候打印出来不是对齐的)
print(testData)

# 第二种方式(有时候打印出来不是对齐的)
for i in testData:
print(i)

# 第三种方式
for i in range(testData.shape[0]):
for j in range(testData.shape[1]):
print("%3d," % testData[i][j], end = "")
print()

结果如下:

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

[[ 2 5 5 12 13 12 5 14 10]
[ 3 2 25 23 23 13 5 20 28]
[28 18 29 13 28 24 6 26 15]
[ 4 8 22 20 2 7 25 3 18]
[21 2 0 7 8 15 13 10 23]
[23 17 12 29 14 5 27 3 20]
[29 25 18 1 0 0 13 29 10]
[23 27 1 12 11 13 3 21 23]
[14 23 12 7 7 3 4 20 2]
[26 24 0 29 20 8 15 23 5]]

[ 2 5 5 12 13 12 5 14 10]
[ 3 2 25 23 23 13 5 20 28]
[28 18 29 13 28 24 6 26 15]
[ 4 8 22 20 2 7 25 3 18]
[21 2 0 7 8 15 13 10 23]
[23 17 12 29 14 5 27 3 20]
[29 25 18 1 0 0 13 29 10]
[23 27 1 12 11 13 3 21 23]
[14 23 12 7 7 3 4 20 2]
[26 24 0 29 20 8 15 23 5]

2, 5, 5, 12, 13, 12, 5, 14, 10,
3, 2, 25, 23, 23, 13, 5, 20, 28,
28, 18, 29, 13, 28, 24, 6, 26, 15,
4, 8, 22, 20, 2, 7, 25, 3, 18,
21, 2, 0, 7, 8, 15, 13, 10, 23,
23, 17, 12, 29, 14, 5, 27, 3, 20,
29, 25, 18, 1, 0, 0, 13, 29, 10,
23, 27, 1, 12, 11, 13, 3, 21, 23,
14, 23, 12, 7, 7, 3, 4, 20, 2,
26, 24, 0, 29, 20, 8, 15, 23, 5,

5. 如何退出解释器提示符

exit() 或者 ctrl + z + enter

6. 字符串的格式化方法

format的使用

7. 运算符的优先级

这个暂时省略

8. 控制知识点

Python中不含有switch语句

while和else连用

for和else连用

9. range函数的使用

注意range每次只会生成一个数字,如果你希望获得完整的数字列表,要在使用 range() 时调用 list() 。

10. 函数知识点

函数变量的作用域,函数传递参数

return None的作用

pass的作用

11. 文档字符串

Python 有一个甚是优美的功能称作文档字符串

print(print_max.__doc__)

12. 三种调用模块的方式:

import

form

from *

模块的名字:

if __name__ == ‘__main__‘:

13. 其它

内置的dir()函数

14. 数据结构:

列表

元组

字典

集合

15. 列表的倒序输出

a[::-1]

16. 帮助

使用help(list) 来查看各个类的使用说明

17. 更多的关于字符串的内容

startswith()

if ‘a’ in name:

name.find()

join的用法

这些用法都可以使用 help(str) 来查看

18. 关于面向对象

类和对象(实例)的关系

字段与方法(注意字段有两种类型,而方法只能是类的方法)

类变量与对象变量

约定:任何在类或对象之中使用的变量其命名应以下划线开头,其它所有非此格式的名称都将是公开的,并可以为其它任何类或对象所使用。请记得这只是一个约定,Python 并不强制如此(除了双下划线前缀这点)。

继承

19. 其它

反向字符串:

去除表达符号:

关于ASCII码的范围,以及与字符串之间的转换关系 ord chr

pickle模块

20. 异常

try except else 语句

try finally 语句

with 语句

21. 一些标准库

sys

os

日志模块的使用(logging)

22. 两个变量交换顺序

23. lambda 表格

24. 列表推导表达式

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)

25. 断言语句

assert

26. 装饰器

27. 将字符串全部修改为大小或小写

1
2
3
4
# 将字符串全部修改为大写或者小写
name = 'Ada Lovelace'
print(name.upper())
print(name.lower())

28. 删除字符串的两端空格

1
2
3
4
5
6
7
8
9
10
# 删除空白
favorite_language = 'python '
print('%r' % favorite_language)
print('%r' % favorite_language.rstrip())
print('%r' % favorite_language)

# 注意两点
# 1. 只能删除末尾
# 2. 这种删除只是暂时的
# rstrip, lstrip, strip 分别对应删除右,左以及两边都删除

29. 在列表中添加和删除元素

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
# 在列表中添加和删除元素

'''
在末尾添加:append
在中间插入:a.insert(2, 'yourthing')
从删除元素:del

使用del可删除任何位置处的列表元素,条件是知道其索引
a = [1,2,3]
print(a)
del a[0]
print(a)

方法pop()可删除列表末尾的元素
a.pop()

方法pop()可删除列表指定位置的元素
a.pop(2)

如果你只知道要删除的元素的值,可使用方法remove()。
方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要
使用循环来判断是否删除了所有这样的值

'''

a = [1,2,3,4,5,6]
print(a)
del a[0]
print(a)
b = a.pop(1)
print(a)
print(b)
a.remove(6)
print(a)

# 结果如下
'''
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
[2, 4, 5, 6]
3
[2, 4, 5]
'''

31. 列表反向

1
2
3
4
5
# help(list.reverse
c = [1,2,3]
print(c)
c.reverse()
print(c)

思考:

  1. 如何去除字符串中的特定字符
  2. 如何转换字符串的大小写
  3. 列表排序,sort()以及sorted()

其它

以下是一段Python的测试代码,用来绘制小猪佩奇:

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
绘制小猪佩奇
"""
from turtle import *
1

def nose(x,y):
"""画鼻子"""
penup()
# 将海龟移动到指定的坐标
goto(x,y)
pendown()
# 设置海龟的方向(0-东、90-北、180-西、270-南)
setheading(-30)
begin_fill()
a = 0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i <90:
a = a + 0.08
# 向左转3度
left(3)
# 向前走
forward(a)
else:
a = a - 0.08
left(3)
forward(a)
end_fill()
penup()
setheading(90)
forward(25)
setheading(0)
forward(10)
pendown()
# 设置画笔的颜色(红, 绿, 蓝)
pencolor(255, 155, 192)
setheading(10)
begin_fill()
circle(5)
color(160, 82, 45)
end_fill()
penup()
setheading(0)
forward(20)
pendown()
pencolor(255, 155, 192)
setheading(10)
begin_fill()
circle(5)
color(160, 82, 45)
end_fill()


def head(x, y):
"""画头"""
color((255, 155, 192), "pink")
penup()
goto(x,y)
setheading(0)
pendown()
begin_fill()
setheading(180)
circle(300, -30)
circle(100, -60)
circle(80, -100)
circle(150, -20)
circle(60, -95)
setheading(161)
circle(-300, 15)
penup()
goto(-100, 100)
pendown()
setheading(-30)
a = 0.4
for i in range(60):
if 0<= i < 30 or 60 <= i < 90:
a = a + 0.08
lt(3) #向左转3度
fd(a) #向前走a的步长
else:
a = a - 0.08
lt(3)
fd(a)
end_fill()


def ears(x,y):
"""画耳朵"""
color((255, 155, 192), "pink")
penup()
goto(x, y)
pendown()
begin_fill()
setheading(100)
circle(-50, 50)
circle(-10, 120)
circle(-50, 54)
end_fill()
penup()
setheading(90)
forward(-12)
setheading(0)
forward(30)
pendown()
begin_fill()
setheading(100)
circle(-50, 50)
circle(-10, 120)
circle(-50, 56)
end_fill()


def eyes(x,y):
"""画眼睛"""
color((255, 155, 192), "white")
penup()
setheading(90)
forward(-20)
setheading(0)
forward(-95)
pendown()
begin_fill()
circle(15)
end_fill()
color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()
color((255, 155, 192), "white")
penup()
seth(90)
forward(-25)
seth(0)
forward(40)
pendown()
begin_fill()
circle(15)
end_fill()
color("black")
penup()
setheading(90)
forward(12)
setheading(0)
forward(-3)
pendown()
begin_fill()
circle(3)
end_fill()


def cheek(x,y):
"""画脸颊"""
color((255, 155, 192))
penup()
goto(x,y)
pendown()
setheading(0)
begin_fill()
circle(30)
end_fill()


def mouth(x,y):
"""画嘴巴"""
color(239, 69, 19)
penup()
goto(x, y)
pendown()
setheading(-80)
circle(30, 40)
circle(40, 80)


def setting():
"""设置参数"""
pensize(4)
# 隐藏海龟
hideturtle()
colormode(255)
color((255, 155, 192), "pink")
setup(840, 500)
speed(10)


def main():
"""主函数"""
setting()
nose(-100, 100)
head(-69, 167)
ears(0, 160)
eyes(0, 140)
cheek(80, 10)
mouth(-20, 30)
done()


if __name__ == '__main__':
main()
-------------本文结束感谢您的阅读-------------