
作者 | 许向武
责编 | 郭芮
出品 | CSDN 博客

for – else
print(i)
else:
print(i, ‘我是else’)
1
2
3
4
4 我是else
if i > 2:
print(i)
else:
print(i, ‘我是else’)
3
4
4 我是else
if i>2:
print(i)
break
else:
print(i, ‘我是else’)
3

一颗星()和两颗星(*)
s = 0
for item in args:
s += item
return s
> multi_sum(3,4,5)
12
print(‘姓名:%s,年龄:%d,性别:%s’%(name, age, gender))
print(args)
print(kwds)
> do_something(‘xufive’, 50, ‘男’, 175, 75, math=99, english=90)
姓名:xufive,年龄:50,性别:男
(175, 75)
{‘math’: 99, ‘english’: 90}

三元表达式
>>> if y < 0:
print(‘y是一个负数’)
else:
print(‘y是一个非负数’)
y是一个非负数
>> print(‘y是一个负数’ if y < 0 else ‘y是一个非负数’)
y是一个非负数
> x = –1 if y < 0 else 1
> x
1

with – as
try:
contents = fp.readlines()
finally:
fp.close()
contents = fp.readlines()

列表推导式
> result = list()
> for i in a:
result.append(i*i)
> result
[1, 4, 9, 16, 25]
> result = [i*i for i in a]
> result
[1, 4, 9, 16, 25]

列表索引的各种骚操作
> a[2:4]
[2, 3]
> a[3:]
[3, 4, 5]
> a[1:]
[1, 2, 3, 4, 5]
> a[:]
[0, 1, 2, 3, 4, 5]
> a[::2]
[0, 2, 4]
> a[1::2]
[1, 3, 5]
> a[-1]
5
> a[-2]
4
> a[1:-1]
[1, 2, 3, 4]
> a[::-1]
[5, 4, 3, 2, 1, 0]
> b = [‘a’, ‘b’]
> a[2:2] = b
> a
[0, 1, ‘a’, ‘b’, 2, 3, 4, 5]
> a[3:6] = b
> a
[0, 1, ‘a’, ‘a’, ‘b’, 4, 5]

lambda函数
<function <lambda> at 0x000001B2DE5BD598>
> (lambda x,y: x+y)(3,4) # 因为匿名函数没有名字,使用的时候要用括号把它包起来
> sorted(a, key=lambda x:x[‘name’]) # 按姓名排序
[{‘name’: ‘A’, ‘age’: 30}, {‘name’: ‘B’, ‘age’: 50}, {‘name’: ‘C’, ‘age’: 40}]
> sorted(a, key=lambda x:x[‘age’]) # 按年龄排序
[{‘name’: ‘A’, ‘age’: 30}, {‘name’: ‘C’, ‘age’: 40}, {‘name’: ‘B’, ‘age’: 50}]
>>> for item in map(lambda x:x*x, a):
print(item, end=‘, ‘)
1, 4, 9,

yield 以及生成器和迭代器
> a_iter = iter(a)
> a_iter
<list_iterator object at 0x000001B2DE434BA8>
> for i in a_iter:
print(i, end=‘, ‘)
1, 2, 3,
result = list()
for i in range(n):
result.append(pow(i,2))
return result
> print(get_square(5))
[0, 1, 4, 9, 16]
for i in range(n):
yield(pow(i,2))
> a = get_square(5)
> a
<generator object get_square at 0x000001B2DE5CACF0>
> for i in a:
print(i, end=‘, ‘)
0, 1, 4, 9, 16,

装饰器
> def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print(‘耗时%0.3f’%(t1-t0,))
return wrapper
> @timer
def do_something(delay):
print(‘函数do_something开始’)
time.sleep(delay)
print(‘函数do_something结束’)
> do_something(3)
函数do_something开始
函数do_something结束
耗时3.077

巧用断言assert
assert(isinstance(delay, (int,float))), ‘函数参数必须为整数或浮点数’
print(‘开始睡觉’)
time.sleep(delay)
print(‘睡醒了’)
> i_want_to_sleep(1.1)
开始睡觉
睡醒了
> i_want_to_sleep(2)
开始睡觉
睡醒了
> i_want_to_sleep(‘2’)
Traceback (most recent call last):
File “<pyshell#247>”, line 1, in <module>
i_want_to_sleep(‘2’)
File “<pyshell#244>”, line 2, in i_want_to_sleep
assert(isinstance(delay, (int,float))), ‘函数参数必须为整数或浮点数’
AssertionError: 函数参数必须为整数或浮点数
