首先,列表推导式通常很容易阅读,这里有一个简单的例子:
[x for x in seq if x != 2]
翻译为:
result = []
for x in seq:
if x != 2:
result.append(x)
您无法阅读此代码的原因是因为它不是我所说的in this question 的可读和hacky 代码:
def f8(seq):
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
翻译为:
def f8(seq):
seen = set()
result = []
for x in seq:
if x not in seen and not seen.add(x): # not seen.add(...) always True
result.append(x)
并且依赖于set.add 是一个始终返回None 的就地方法这一事实,因此not None 的计算结果为True。
>>> s = set()
>>> y = s.add(1) # methods usually return None
>>> print s, y
set([1]) None
之所以这样编写代码,是为了偷偷利用 Python 的列表理解速度优化。
如果 Python 方法修改数据结构,通常会返回 None(pop 是例外之一)
我还注意到,目前公认的这样做的方式 (2.7+) 更具可读性并且不使用 hack,如下所示:
>>> from collections import OrderedDict
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(OrderedDict.fromkeys(items))
[1, 2, 0, 3]
字典键必须是唯一的,因此会过滤掉重复项。