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

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

快速链接到答案:

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


当前回答

您可以使用zip轻松地转置数组。

a = [(1,2), (3,4), (5,6)]
zip(*a)
# [(1, 3, 5), (2, 4, 6)]

其他回答

Python有一些非常意想不到的异常:

进口

这允许您在缺少库时导入替代库

try:
    import json
except ImportError:
    import simplejson as json

迭代

For循环在内部执行此操作,并捕获StopIteration:

iter([]).next()
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    iter(a).next()
StopIteration

断言

>>> try:
...     assert []
... except AssertionError:
...     print "This list should not be empty"
This list should not be empty

虽然这对于一次检查来说比较冗长,但是使用相同错误消息混合异常和布尔运算符的多次检查可以通过这种方式缩短。

Dict的构造函数接受关键字参数:

>>> dict(foo=1, bar=2)
{'foo': 1, 'bar': 2}

Metaclasses

Python中的元类是什么?

能够替换甚至像文件删除,文件打开等-语言库的直接操作。这在测试时是一个巨大的优势。你不必把所有东西都包装在复杂的容器里。只需要替换一个函数/方法就可以了。这也被称为猴子修补。

Doctest:同时进行文档和单元测试。

从Python文档中提取的示例:

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

def _test():
    import doctest
    doctest.testmod()    

if __name__ == "__main__":
    _test()