将嵌套列表中的每个元素乘以2

时间:2018-01-23 19:11:25

标签: python list nested

问题是:定义一个名为ex_4的函数,它将内部列表中的每个元素乘以2.例如:

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

这就是我所拥有的......

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])

这将返回我正在寻找的结果,但是答案不会作为嵌套列表返回。我也希望能够输入其他列表,而不必继续添加LL [3],LL [4]等。

1 个答案:

答案 0 :(得分:2)

In that case you can also nest the maps

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.