首页 > Python基础教程 >
-
30个Python常用小技巧(3)
7、交互环境下的“_”操作符
在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
8、字典/集合推导
1
2
3
4
|
testDic = {i: i * i for i in range ( 10 )} testSet = {i * 2 for i in range ( 10 )} print (testDic) print (testSet) |
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
9、调试脚本
用pdb模块设置断点
1
2
|
import pdb pdb.ste_trace() |
10、开启文件分享
python允许开启一个HTTP服务器从根目录共享文件
1
|
python - m http.server |
11、检查python中的对象
1
2
|
test = [ 1 , 3 , 5 , 7 ] print ( dir (test)) |
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
1
2
|
test = range ( 10 ) print ( dir (test)) |
['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
12、简化if语句
1
2
3
4
|
# use following way to verify multi values if m in [ 1 , 2 , 3 , 4 ]: # do not use following way if m = = 1 or m = = 2 or m = = 3 or m = = 4 : |