1、原地交换两个数字
2、链状比较操作符
3、使用三元操作符来实现条件赋值
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
4、多行字符串
5、存储列表元素到新的变量
6、打印引入模块的绝对路径
7、交互环境下的“_”操作符
在python控制台,不论我们测试一个表达式还是调用一个方法,结果都会分配给一个临时变量“_”
>>> 1+1
2
>>> _
2
8、字典/集合推导
9、调试脚本
用pdb模块设置断点
10、开启文件分享
python允许开启一个HTTP服务器从根目录共享文件
11、检查python中的对象
12、简化if语句
13、运行时检测python版本
14、组合多个字符串
15、四种翻转字符串、列表的方式
16、用枚举在循环中找到索引
17、定义枚举量
18、从方法中返回多个值
19、使用*运算符unpack函数参数
20、用字典来存储表达式
21、计算任何数的阶乘
22、找到列表中出现次数最多的数
23、重置递归限制
python限制递归次数到1000,可以用下面方法重置
24、检查一个对象的内存使用
25、使用slots减少内存开支
26、用lambda 来模仿输出方法
27、从两个相关序列构建一个字典
28、搜索字符串的多个前后缀
29、不使用循环构造一个列表
30、实现switch-case语句
31、简化导入模块名
32、在一行中捕获多个异常
33、查找列表中某个元素的下标
34、包管理
Python世界最棒的地方之一,就是大量的第三方程序包。同样,管理这些包也非常容易。按照惯例,会在 requirements.txt 文件中列出项目所需要的包。每个包占一行,通常还包含版本号。
pelican==3.3
Markdown
pelican-extended-sitemap==1.0.0
35、名称前的单下划线(如:_shahriar)
程序员使用名称前的单下划线,用于指定该名称属性为“私有”。这有点类似于惯例,为了使其他人(或你自己)使用这些代码时将会知道以“_”开头的名称只供内部使用。正如Python文档中所述:
以下划线 __ 为前缀的名称(如_pam)应该被视为API中非公开的部分(不管是函数、方法还是数据成员)。此时,应该将它们看作是一种实现细节,在修改它们时无需对外部通知。
正如上面所说,这确实类似一种惯例,因为它对解释器来说确实有一定的意义,如果你写了代码 : from <模块/包名> import *
,那么以 _ 开头的名称都不会被导入,除非模块或包中的 __all__
列表显式地包含了它们。了解更多请查看 Importing * in Python
36、 隐藏特性 --- print 重定向输出到文件
注意打开的模式: “w+” 而不能 “w” , 当然 “a” 是可以的
>>>print>>open("somefile","w+")
37、隐藏特性 --- isinstance可以接收一个元组
这个真的鲜为人知, 我们可以用 isinstance(x, (float, int)) 来判断 x 是不是数,也就是那个元组里面是 或 的关系,只要是其中一个的实例就返回 True。
>>>isinstance(1,(float,int))
True
>>>isinstance(1.3,(float,int))
True
>>>isinstance("1.3",(float,int))
False