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

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

快速链接到答案:

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


当前回答

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

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

其他回答

>>> from functools import partial
>>> bound_func = partial(range, 0, 10)
>>> bound_func()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bound_func(2)
[0, 2, 4, 6, 8]

不是真正的隐藏特性,但是partial对于函数的后期计算非常有用。

你可以在初始调用中绑定尽可能多的或尽可能少的参数到你想要的partial,并在以后使用任何剩余的参数调用它(在这个例子中,我已经将begin/end参数绑定到range,但第二次使用step arg调用它)

请参见文档。

原始字符串中的反斜杠仍然可以转义引号。看到这个:

>>> print repr(r"aaa\"bbb")
'aaa\\"bbb'

注意,反斜杠和双引号都出现在最后的字符串中。

因此,你不能用反斜杠来结束一个原始字符串:

>>> print repr(r"C:\")
SyntaxError: EOL while scanning string literal
>>> print repr(r"C:\"")
'C:\\"'

这是因为实现原始字符串是为了帮助编写正则表达式,而不是为了编写Windows路径。在Gotcha - Windows文件名中的反斜杠上阅读关于这个的长讨论。

如果你在你的类上使用描述符,Python完全绕过__dict__键,这使得它成为一个存储这些值的好地方:

>>> class User(object):
...  def _get_username(self):
...   return self.__dict__['username']
...  def _set_username(self, value):
...   print 'username set'
...   self.__dict__['username'] = value
...  username = property(_get_username, _set_username)
...  del _get_username, _set_username
... 
>>> u = User()
>>> u.username = "foo"
username set
>>> u.__dict__
{'username': 'foo'}

这有助于保持dir()干净。

内置base64, zlib和rot13编解码器

字符串有编码和解码方法。通常这用于将str转换为unicode,反之亦然,例如u = s.c encode('utf8')。但还有其他一些方便的内置编解码器。使用zlib(和bz2)进行压缩和解压,无需显式导入:

>>> s = 'a' * 100
>>> s.encode('zlib')
'x\x9cKL\xa4=\x00\x00zG%\xe5'

类似地,你可以编码和解码base64:

>>> 'Hello world'.encode('base64')
'SGVsbG8gd29ybGQ=\n'
>>> 'SGVsbG8gd29ybGQ=\n'.decode('base64')
'Hello world'

当然,你也可以:

>>> 'Secret message'.encode('rot13')
'Frperg zrffntr'

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!