@[toc]
关键字
>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
上下文管理器
with open("test.txt", "w") as f:
#上下文管理器,常在资源管理中用到,能够处理异常
拉平列表
ll=[[1,3,4],[5,6,7,8],[9,10,11]]
ll_f=[e for ele in ll for e in ele] #flatten list
按列遍历矩阵
matrix=[[1,2,3],[2,3,4],[3,4,5]]
• matrix2=[[row[i] for row in matrix] for i in
range(3)]
#按列遍历矩阵
字典的有序输出
for key in sorted(dic.keys()):
print(key,dic[key])
#字典的有序输出
构造有序字典
#如何构建有序字典
import collections
dic = collections.OrderedDict()
dic=collections.OrderedDict(sorted(unsorted_d.items(), key=lambda dc:dc[1], reverse = True))
eval
eval(str)
#用来计算在字符串中的有效Python表达式,并返回一个对象
推导式
#推导式
a=[x**2 for x in range(6)]
a=list(map(lambda x:x**2,range(6)))
pis=[str(round(math.pi, i)) for i in range(1,6)]
a=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] #(跟zip的区别)
网友评论