by benhoyt · 14y ago · 0 comments
One built-in function I basically never use is zip(). I know how it's used and what it does, and I grok the names/ages types of examples that are always used to explain it. But I've simply never needed it in real code. Anyone else use it often, and in what contexts?
>>> m = [(1,2,3), (4,5,6), (7,8,9)]
>>> zip(*m)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> m = [(1,2,3), (4,5,6), (7, 8)]
>>> zip(*m)
[(1, 4, 7), (2, 5, 8)] # Wrong
>>> from itertools import izip_longest
>>> list(izip_longest(*m, fillvalue=None))
[(1, 4, 7), (2, 5, 8), (3, 6, None)] >>> keys = ["foo", "bar", "spam", "egg"]
>>> values = [1, 2, 3, 4]
>>> dict(zip(keys, values))
{'egg': 4, 'foo': 1, 'bar': 2, 'spam': 3}
Quite useful when you MGET from Redis. for a, b in zip(list_a, list_b):
print a + b from itertools import izip
izip(xrange(len(seq)), seq) zip(range(len(seq)), seq)You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Haskell:
sum(zipWith (*) [1,2,3][3,2,1])
Python is not inherently functional, just supports a few convenience idioms. It has zip, but no zipWith. As a result you have to use list comprehension to perform the same: sum([x*y for (x,y) in zip([1,2,3][3,2,1])]) sum(map(operator.mul, [1,2,3], [3,2,1])) def lca(a,b)
a.ancestors.zip(b.ancestors).take_while { |a,b| a == b }.last
end