What would be the proper conversion of the following map
statement into a for
loop?
map(lambda x: map(lambda y: map(lambda z: x*y*z, [5,6]), [3,4]), [1,2])
# [[[15, 18], [20, 24]], [[30, 36], [40, 48]]]
My first attempt was something like:
x_tmp = []
for x in [1,2]:
y_tmp = []
for y in [3,4]:
z_tmp = []
for z in [5,6]:
z_tmp.append(x*y*z)
y_tmp.append(z_tmp)
x_tmp.append(y_tmp)
x_tmp
# [[[15, 18], [20, 24]], [[30, 36], [40, 48]]]
But this seems so odd that I can't imagine that would be the actual translation of it. Is there something closer to how map
works that can be shown with a for
loop?
I thought maybe it would be close to:
[x*y*z for x in [1,2] for y in [3,4] for z in [5,6]]
# [15, 18, 20, 24, 30, 36, 40, 48]
But that seems to lose all the nesting and do a flat mapping instead.
To do the list-comprehension way it seems not only does it need to be nested, but the args also need to be reversed, for example:
>>> [[[x*y*z for z in [5,6]] for y in [3,4]] for x in [1,2]]
# [[[15, 18], [20, 24]], [[30, 36], [40, 48]]]