有很多方法可以编写计算直方图的 Python 程序。
通过直方图,我的意思是一个函数,它计算对象在 an 中的出现iterable
并输出字典中的计数。例如:
>>> L = 'abracadabra'
>>> histogram(L)
{'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2}
编写此函数的一种方法是:
def histogram(L):
d = {}
for x in L:
if x in d:
d[x] += 1
else:
d[x] = 1
return d
有没有更简洁的方法来编写这个函数?
如果我们在 Python 中有字典推导式,我们可以这样写:
>>> { x: L.count(x) for x in set(L) }
但由于 Python 2.6 没有它们,我们必须写:
>>> dict([(x, L.count(x)) for x in set(L)])
虽然这种方法可能是可读的,但效率不高:L 被多次遍历。此外,这不适用于单寿命发电机;该函数应该同样适用于迭代器生成器,例如:
def gen(L):
for x in L:
yield x
我们可能会尝试使用reduce
函数(RIP):
>>> reduce(lambda d,x: dict(d, x=d.get(x,0)+1), L, {}) # wrong!
糟糕,这不起作用:键名是'x'
,而不是x
。:(
我结束了:
>>> reduce(lambda d,x: dict(d.items() + [(x, d.get(x, 0)+1)]), L, {})
(在 Python 3 中,我们必须写list(d.items())
而不是d.items()
,但这是假设的,因为那里没有reduce
。)
请用更好,更易读的单行符击败我!;)