Python编程语言中有哪些鲜为人知但很有用的特性?

尽量将答案限制在Python核心。 每个回答一个特征。 给出一个例子和功能的简短描述,而不仅仅是文档链接。 使用标题作为第一行标记该特性。

快速链接到答案:

参数解包 牙套 链接比较运算符 修饰符 可变默认参数的陷阱/危险 描述符 字典默认的.get值 所以测试 省略切片语法 枚举 其他/ 函数作为iter()参数 生成器表达式 导入该 就地值交换 步进列表 __missing__物品 多行正则表达式 命名字符串格式化 嵌套的列表/生成器推导 运行时的新类型 .pth文件 ROT13编码 正则表达式调试 发送到发电机 交互式解释器中的制表符补全 三元表达式 试着/ / else除外 拆包+打印()函数 与声明


当前回答

测试键是否在字典中的简单方法:

>>> 'key' in { 'key' : 1 }
True

>>> d = dict(key=1, key2=2)
>>> if 'key' in d:
...     print 'Yup'
... 
Yup

其他回答

Python的禅宗

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

主要信息:)

import this
# btw look at this module's source :)

De-cyphered:

蒂姆·彼得斯的《Python之禅》 美总比丑好。 显性比隐性好。 简单比复杂好。 复杂胜过复杂。 扁平比嵌套好。 稀疏比密集好。 可读性。 特殊情况并不特别到可以打破规则。 尽管实用性胜过纯洁性。 错误绝不能悄无声息地过去。 除非明确保持沉默。 面对模棱两可,拒绝猜测的诱惑。 应该有一种——最好只有一种——明显的方法来做到这一点。 除非你是荷兰人,否则这种方式一开始可能并不明显。 现在总比没有好。 虽然永远不比现在更好。 如果实现很难解释,那就是一个坏主意。 如果实现很容易解释,这可能是一个好主意。 名称空间是一个非常棒的想法——让我们多做一些吧!

操作符重载的集合内置:

>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b # Union
{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection
{3, 4}
>>> a < b # Subset
False
>>> a - b # Difference
{1, 2}
>>> a ^ b # Symmetric Difference
{1, 2, 5, 6}

更多详细信息请参阅标准库参考:Set Types

模块操作符中的Getter函数

模块操作符中的函数attrgetter()和itemgetter()可用于生成用于排序和搜索对象和字典的快速访问函数

Python库文档中的第6.7章

pdb - Python调试器

作为程序员,要进行严肃的程序开发,首先需要的东西之一是调试器。Python有一个内置的模块,叫做pdb(自然是“Python调试器”的缩写!)

http://docs.python.org/library/pdb.html