Question: List comprehension equivalent to map on two lists in parallel

Question

List comprehension equivalent to map on two lists in parallel

Answers 1
Added at 2016-12-26 00:12
Tags
Question

I understand that with one list argument map() can be replaced by a list comprehension. For example

map(lambda x : x**2, range(5))

can be replaced with

[x**2 for x in range(5)]

Now how would I do something similar for two parallel lists. In other words, I have a line of code with the following pattern:

map(func, xs, ys)

where func() takes two arguments.

How can I do the same thing with a list comprehension?

Answers to

List comprehension equivalent to map on two lists in parallel

nr: #1 dodano: 2016-12-26 00:12

map() with multiple arguments is the equivalent of using the zip() function on those extra arguments. Use zip() in a list comprehension to do the same:

[func(x, y) for x, y in zip(xs, ys)]

Generally speaking, any map(func, a1, a2, .., an) expression can be transformed to a list comprehension with [func(*args) for args in zip(a1, a2, .., an)].

Source Show
◀ Wstecz