Kevin
Kevin

Reputation: 33

List comprehension using multiple lists

I was unable to determine a Pythonic way for generating a list using list comprehension from multiple lists. I'm trying to generate a list that implements the following function:

vbat = Vmax - a + b + c

Where Vmax is a constant but a, b and c are lists. I was hoping I could do something that's easy to read like this:

vbat = [Vmax - x + y + z for x in a and y in b and z in c]

I know that I can use the map operator to make a new combined list and then use a list comprehension on the new list but it seems a little ugly and hard to read. The code that I know would work is shown below:

newlist = map(sub,map(add,b,c),a)
vbat = [Vmax + x for x in newlist]

Is there a solution to this that is friendlier for the reader? Thanks in advance.

Upvotes: 3

Views: 4152

Answers (1)

lungj
lungj

Reputation: 729

The zip function can combine multiple lists into a sequence of tuples:

[Vmax - a_el + b_el + c_el for (a_el, b_el, c_el) in zip(a, b, c)]

Upvotes: 7

Related Questions