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

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

快速链接到答案:

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


当前回答

模块操作符中的Getter函数

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

Python库文档中的第6.7章

其他回答

将元组传递给内置函数

很多Python函数接受元组,但看起来并不像。例如,你想测试你的变量是否是一个数字,你可以这样做:

if isinstance (number, float) or isinstance (number, int):  
   print "yaay"

但如果你传递给我们元组,这看起来更干净:

if isinstance (number, (float, int)):  
   print "yaay"

如果你在你的类上使用描述符,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()干净。

切片运算符中的step参数。例如:

a = [1,2,3,4,5]
>>> a[::2]  # iterate over the whole list in 2-increments
[1,3,5]

特殊情况x[::-1]是“x反转”的有用习语。

>>> a[::-1]
[5,4,3,2,1]

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

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

元组在for循环、列表推导式和生成器表达式中的解包:

>>> l=[(1,2),(3,4)]
>>> [a+b for a,b in l ] 
[3,7]

在这个习语中,用于迭代字典中的(键,数据)对:

d = { 'x':'y', 'f':'e'}
for name, value in d.items():  # one can also use iteritems()
   print "name:%s, value:%s" % (name,value)

打印:

name:x, value:y
name:f, value:e