简体   繁体   中英

multiplying each element in a nested list by 2

The problem is: Define a function called ex_4 that will multiply every element in the inner list by 2. For example:

ex_4([[1, 2, 3], [4, 5], [6, 7, 8]]) ---> [[2, 4, 6], [8, 10], [12, 14, 16]]

Here's what I have.....

def ex_4(LL):
    return list(map(lambda x: x*2, LL[0])), list(map(lambda x: x*2, LL[1])),list(map(lambda x: x*2, LL[2]))

ex_4([[1, 2, 3], [4, 5], [6, 7, 8]])
--> ([2, 4, 6], [8, 10], [12, 14, 16])

This returns the result I'm looking for, however the answer is not returned as a nested list. I'd also like to be able to input additional lists to that, and not have to keep adding LL[3],LL[4], etc.

In that case you can also nest the map s

list(map(lambda L: list(map(lambda x: x*2, L)), LL))

but in this case, it is more elegant here to use nested list comprehension:

[ [ 2*x for x in L ] for L in LL ]

So here the outer list comprehension iterates with L over the elements (sublists) of LL . For every such L , we "yield" the inner list comprehension, where we iterate with x over L and yield 2*x for every element in L .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM