Reloader
Reloader

Reputation: 720

How can I rewrite this map() example using list comprehension?

orders = [ ["34587",("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)], 
           ["34588",("5464", 9, 9.99), ("9744", 9, 44.95)],
           ["34588",("5464", 9, 9.99)],
           ["34587",("8732", 7, 11.99), ("7733",11,18.99), ("9710", 5, 39.95)] ]

I want a new list of as a result, with the first element ("34587") and other elements from tuple multiplied (example: 4*9.99, 18*12.99, 9*44.95)

Can be achieved with map():

list(map(lambda x: [x[0]] + list(map(lambda y: y[1]*y[2], x[1:])), orders))

Result:

[['34587', 39.96, 233.82, 404.55], ['34588', 89.91, 404.55], ['34588', 89.91], ['34587', 83.93, 208.89, 199.75]]

Question is, can this map() example be rewritten as list comprehension?

Thanks.

Upvotes: 0

Views: 118

Answers (1)

Arpegius
Arpegius

Reputation: 5887

As in one comment, map with lambda:

list(map(lambda y: expression_involving_y, elements))

can be exchanged with list comprehensions:

[expression_involving_y for y in elements]

You can start with substituting your inner map:

list(map(lambda x: [x[0]] + list(map(lambda y: y[1]*y[2], x[1:])), orders))

having elements as x[1:] and expression_involving_y as y[1]*y[2] to:

list(map(lambda x: [x[0]] + [ y[1]*y[2] for y in x[1:] ], orders))

And you can repeat the substitution to finally get to your result:

[ [x[0]] + [ y[1]*y[2] for y in x[1:] ] for x in orders ]

Upvotes: 3

Related Questions