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

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

快速链接到答案:

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


当前回答

Mod对负数正确工作

-1 % 5等于4,这是应该的,而不是像JavaScript等其他语言中那样是-1。这使得Python中的“环绕窗口”更干净,你只需要这样做:

index = (index + increment) % WINDOW_SIZE

其他回答

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!

使用不同的起始索引进行枚举

enumerate在这个答案中已经部分涉及了,但最近我发现了enumerate一个更隐藏的特性,我认为值得单独发表,而不仅仅是评论。

从Python 2.6开始,你可以在第二个参数中指定要枚举的起始索引:

>>> l = ["spam", "ham", "eggs"]
>>> list(enumerate(l))
>>> [(0, "spam"), (1, "ham"), (2, "eggs")]
>>> list(enumerate(l, 1))
>>> [(1, "spam"), (2, "ham"), (3, "eggs")]

我发现它非常有用的一个地方是当我枚举对称矩阵的元素时。由于矩阵是对称的,我可以通过只在上三角形上迭代来节省时间,但在这种情况下,我必须在内部for循环中使用不同的起始索引来正确跟踪行和列的索引:

for ri, row in enumerate(matrix):
    for ci, column in enumerate(matrix[ri:], ri):
        # ci now refers to the proper column index

奇怪的是,enumerate的这种行为在help(enumerate)中没有记录,只有在线文档中有记录。

特殊的方法

绝对的权力!

在调试复杂的数据结构时,pprint模块非常方便。

从文件中引用…

>>> import pprint    
>>> stuff = sys.path[:]
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=869440>,
 '',
 '/usr/local/lib/python1.5',
 '/usr/local/lib/python1.5/test',
 '/usr/local/lib/python1.5/sunos5',
 '/usr/local/lib/python1.5/sharedmodules',
 '/usr/local/lib/python1.5/tkinter']

Python的位置和关键字展开可以动态使用,而不仅仅是从存储的列表中使用。

l=lambda x,y,z:x+y+z
a=1,2,3
print l(*a)
print l(*[a[0],2,3])

它通常在以下情况下更有用:

a=[2,3]
l(*(a+[3]))