一、for - else
for i in [1, 2, 3, 4]:
print(i)
else:
print("我是一个美丽的意外:%d" % i)
二、可变参数
Python 函数不仅支持默认参数,也支持可变参数,一颗星表示不限数量的单值参数,两颗星表示不限数量的键值对参数。我们还是举例说明吧:设计一个函数,返回多个输入数值的和。我们固然可以把这些输入数值做成一个list传给函数,但这个方法,远没有使用一颗星的可变参数来得优雅:
def multi_params(*args, **kwargs):
for i in args:
print(i)
print({k[0]: k[1] for k in kwargs.items()})
multi_params(1, 2, 3, 4, a=1,b=9)
三、with - as
系统会自动关闭连接句柄,减低内存泄漏的风险:e.g.
with open(self.output_sentence_entity_file, "w", encoding='utf-8') as outfile:
outfile.write("\n\n")
四、三元表达式
a = ' ' if ('[]' == x or x is np.nan) else x
五、列表推导式
a = [i for i in [1,2,3,4] if i%2==0]
六、lambda函数
print((lambda x, y: x * y)(10, 3))
七、yield 以及生成器和迭代器
def get_multi(n):
for i in range(n):
yield(pow(i, 3))
for i in get_multi(4):
print(i, end=';')
print([i for i in get_multi(4)])
八、断言assert
i=[]
assert type(i) is list
assert type(i) is str
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError
assert isinstance(i, (int, list))
assert isinstance(i, (int, str))
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError
九、装饰器
在每个函数运行的时候要显示当前函数的运行时长,装饰器如何做到简单、优雅。下面的例子,很好地展示了这一点
def timer(func):
import time
def wrapper(*args, **kwargs):
t0 = time.time()
func(*args, **kwargs)
t1 = time.time()
print('%s, time elapsed %.2fs' % (func.__name__, t1 - t0))
return wrapper
@timer
def build():
import time
time.sleep(10)
build()
十、列表索引
l = ['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple', 'Microsoft']
print(l[0:1])
['Google']
print(l[:-1])
['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple']
print(l[0:-1])
['Google', 'Facebook', 'Ins', 'Meta', 'Netflix', 'Apple']
print(l[0::-1])
['Google']
print(l[::-1])
['Microsoft', 'Apple', 'Netflix', 'Meta', 'Ins', 'Facebook', 'Google']
print(l[::-2])
['Microsoft', 'Netflix', 'Ins', 'Google']
print(l[::2])
['Google', 'Ins', 'Netflix', 'Microsoft']
print(l[-1])
Microsoft
十一、zip
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]