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

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

快速链接到答案:

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


当前回答

创建具有相关数据的两个序列的字典

In [15]: t1 = (1, 2, 3)

In [16]: t2 = (4, 5, 6)

In [17]: dict (zip(t1,t2))
Out[17]: {1: 4, 2: 5, 3: 6}

其他回答

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!

创建生成器对象

如果你写

x=(n for n in foo if bar(n))

你可以取出生成器,把它赋值给x,这意味着你可以这样做

for n in x:

这样做的优点是不需要中间存储,如果需要中间存储,则需要中间存储

x = [n for n in foo if bar(n)]

在某些情况下,这可以显著提高速度。

你可以在生成器的末尾附加许多if语句,基本上复制嵌套的for循环:

>>> n = ((a,b) for a in range(0,2) for b in range(4,6))
>>> for i in n:
...   print i 

(0, 4)
(0, 5)
(1, 4)
(1, 5)

一切事物的一等性(“一切事物都是一个物体”),以及这可能造成的混乱。

>>> x = 5
>>> y = 10
>>> 
>>> def sq(x):
...   return x * x
... 
>>> def plus(x):
...   return x + x
... 
>>> (sq,plus)[y>x](y)
20

最后一行创建一个包含这两个函数的元组,然后计算y>x (True)并将其作为元组的索引(通过将其强制转换为int类型,1),然后使用参数y调用该函数并显示结果。

对于进一步的滥用,如果你返回一个带索引的对象(例如一个列表),你可以在末尾添加更多的方括号;如果内容是可调用的,更多的括号,等等。为了更变态,使用这样的代码的结果作为另一个例子中的表达式(即用下面的代码替换y>x):

(sq,plus)[y>x](y)[4](x)

这展示了Python的两个方面——极端的“一切都是一个对象”哲学,以及不恰当或考虑不良的语言语法使用方法,可能导致完全不可读、不可维护的意大利面条代码,适合一个表达式。

舍入整数: Python有round函数,它返回double类型的数字:

 >>> print round(1123.456789, 4)
1123.4568
 >>> print round(1123.456789, 2)
1123.46
 >>> print round(1123.456789, 0)
1123.0

这个函数有一个神奇的特性:

 >>> print round(1123.456789, -1)
1120.0
 >>> print round(1123.456789, -2)
1100.0

如果你需要一个整数作为结果,使用int来转换类型:

 >>> print int(round(1123.456789, -2))
1100
 >>> print int(round(8359980, -2))
8360000

谢谢你,格雷戈。

Monkeypatching对象

Python中的每个对象都有__dict__成员,用于存储对象的属性。所以,你可以这样做:

class Foo(object):
    def __init__(self, arg1, arg2, **kwargs):
        #do stuff with arg1 and arg2
        self.__dict__.update(kwargs)

f = Foo('arg1', 'arg2', bar=20, baz=10)
#now f is a Foo object with two extra attributes

可以利用这一点向对象任意添加属性和函数。这也可以用来创建一个快速和肮脏的结构类型。

class struct(object):
    def __init__(**kwargs):
       self.__dict__.update(kwargs)

s = struct(foo=10, bar=11, baz="i'm a string!')