今天小编给你推荐30个Python实用的小技巧,你肯定会用到,赶紧来收藏吧!如果你想学习python,可以关注并私聊我:python,给你发万元python学习大礼包哦!
1、原地交换两个数字
x, y =10, 20print(x, y)y, x = x, yprint(x, y)
10 20
20 10
2、链状比较操作符
n = 10print(1 < n < 20)print(1 > n <= 9)
True
False
3、使用三元操作符来实现条件赋值
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
y = 20x = 9 if (y == 10) else 8print(x)
8
# 找abc中最小的数
def small(a, b, c): return a if a0
1
3
3
# 列表推导
x = [m**2 if m>10 else m**4 for m in range(50)]print(x)
[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
4、多行字符串
multistr = "select * from multi_row where row_id < 5"print(multistr)select * from multi_row where row_id < 5multistr = """select * from multi_rowwhere row_id < 5"""print(multistr)select * from multi_rowwhere row_id < 5multistr = ("select * from multi_row""where row_id < 5""order by age")print(multistr)select * from multi_rowwhere row_id < 5order by age
5、存储列表元素到新的变量
testList = [1, 2, 3]x, y, z = testList # 变量个数应该和列表长度严格一致print(x, y, z)
1 2 3
6、打印引入模块的绝对路径
import threadingimport socketprint(threading)print(socket)
7、交互环境下的“_”操作符
在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
8、字典/集合推导
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模块设置断点
import pdbpdb.ste_trace()
10、开启文件分享
python允许开启一个HTTP服务器从根目录共享文件
python -m http.server
11、检查python中的对象
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']
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语句
# use following way to verify multi valuesif m in [1, 2, 3, 4]:# do not use following wayif m==1 or m==2 or m==3 or m==4:
13、运行时检测python版本
import sysif not hasattr(sys, "hexversion") or sys.version_info != (2, 7): print("sorry, you are not running on python 2.7") print("current python version: