Consider the following list of lists:
arr = [[1, 2, 3], [3, 2, 1]]
I want to get the square of it, using map
with a lambda
function. The result should be:
arr = [[1, 4, 9], [9, 4, 1]]
I tried this:
print(list(map(lambda x: [lst**2 for lsts in arr for lst in lsts], arr)))
But I get that as answer:
[[1, 4, 9, 9, 4, 1], [1, 4, 9, 9, 4, 1]]
CodePudding user response:
Try this:
arr = list(map(lambda List: [x**2 for x in List], arr))
# Output : [[1, 4, 9], [9, 4, 1]]
You can also use nested mapping:
arr = list(map(lambda List: list(map(lambda x: x**2, List)), arr))
# or
square = lambda x: x**2
arr = list(map(lambda List: list(map(square, List)), arr))
CodePudding user response:
Something like this:
arr = [[1,2,3],[3,2,1]]
output = list(map(lambda x: [i**2 for i in x], arr))
print(output)
CodePudding user response:
This works combining both lambda
s and list-comprehension:
arr = [[1, 2, 3], [4, 5, 6]]
print(list(map(lambda x: [i * i for i in x], arr)))
Output:
[[1, 4, 9], [16, 25, 36]]
CodePudding user response:
Consider using numpy:
arr = [[1,2,3],[3,2,1]]
arr_numpy = np.array(arr)
result = arr_numpy ** 2
CodePudding user response:
You mention that you want to use map
and lambda
but for reference, you can do this just using list comprehensions,
[[y * y for y in x] for x in arr]