在Python中,Haskell的zipWith函数的类比是什么?
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Run Code Online (Sandbox Code Playgroud)
Ign*_*ams 51
map()
map(operator.add, [1, 2, 3], [3, 2, 1])
Run Code Online (Sandbox Code Playgroud)
虽然zip()通常使用LC .
[x + y for (x, y) in zip([1, 2, 3], [3, 2, 1])]
Run Code Online (Sandbox Code Playgroud)
dsi*_*ign 40
如果您愿意,您可以创建自己的,但在Python中我们主要做
list_c = [ f(a,b) for (a,b) in zip(list_a,list_b) ]
Run Code Online (Sandbox Code Playgroud)
因为Python本身并不具备功能.它恰好支持一些方便的习语.
hei*_*991 10
你可以使用map:
>>> x = [1,2,3,4]
>>> y = [4,3,2,1]
>>> map(lambda a, b: a**b, x, y)
[1, 8, 9, 4]
Run Code Online (Sandbox Code Playgroud)
一个懒惰zipWith的itertools:
import itertools
def zip_with(f, *coll):
return itertools.starmap(f, itertools.izip(*coll))
Run Code Online (Sandbox Code Playgroud)
此版本概括了zipWith任意数量的iterables 的行为.