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

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

快速链接到答案:

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


当前回答

设置/ frozenset

可能一个容易被忽略的python内置程序是“set/frozenset”。

当你有一个像这样的列表[1,2,1,1,2,3,4]并且只想要像[1,2,3,4]这样的唯一性时很有用。

使用set()这就是你得到的结果:

>>> x = [1,2,1,1,2,3,4] 
>>> 
>>> set(x) 
set([1, 2, 3, 4]) 
>>>
>>> for i in set(x):
...     print i
...
1
2
3
4

当然,要得到列表中唯一的个数:

>>> len(set([1,2,1,1,2,3,4]))
4

你也可以使用set(). is子集()来判断一个列表是否是另一个列表的子集:

>>> set([1,2,3,4]).issubset([0,1,2,3,4,5])
True

从Python 2.7和3.0开始,你可以使用花括号来创建一个集合:

myset = {1,2,3,4}

以及集合理解:

{x for x in stuff}

详情如下: http://docs.python.org/library/stdtypes.html#set

其他回答

不是“隐藏”,而是很有用,不常用

像这样快速创建字符串连接函数

 comma_join = ",".join
 semi_join  = ";".join

 print comma_join(["foo","bar","baz"])
 'foo,bar,baz

and

能够更优雅地创建字符串列表,而不是引号,逗号混乱。

l = ["item1", "item2", "item3"]

取而代之的是

l = "item1 item2 item3".split()

将值发送到生成器函数。例如有这样的函数:

def mygen():
    """Yield 5 until something else is passed back via send()"""
    a = 5
    while True:
        f = (yield a) #yield a and possibly get f in return
        if f is not None: 
            a = f  #store the new value

您可以:

>>> g = mygen()
>>> g.next()
5
>>> g.next()
5
>>> g.send(7)  #we send this back to the generator
7
>>> g.next() #now it will yield 7 until we send something else
7
>>> 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调用它)

请参见文档。

嵌套列表推导式和生成器表达式:

[(i,j) for i in range(3) for j in range(i) ]    
((i,j) for i in range(4) for j in range(i) )

它们可以替换大量嵌套循环代码。

内置方法或函数不实现描述符协议,这使得不可能做这样的事情:

>>> class C(object):
...  id = id
... 
>>> C().id()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: id() takes exactly one argument (0 given)

然而,你可以创建一个小的绑定描述符来实现这一点:

>>> from types import MethodType
>>> class bind(object):
...  def __init__(self, callable):
...   self.callable = callable
...  def __get__(self, obj, type=None):
...   if obj is None:
...    return self
...   return MethodType(self.callable, obj, type)
... 
>>> class C(object):
...  id = bind(id)
... 
>>> C().id()
7414064