2

I want to apply some functions to certain elements in an array of arrays.

def func_1(num):
    return num+1

def func_2(num):
    return num+2

test_array = [ [10,1],[10,1],[11,2]]

I want to apply function func_1 to first element of each array and function func_2 to second element of each array.

The result array will look like this;

result_array = [ [11,3],[11,3],[12,4]]

I am using python 3.7

2 Answers 2

3

You could use map():

def func_1(num):
    return num+1

def func_2(num):
    return num+2

test_array = [ [10,1],[10,1],[11,2]]

out = list(map(lambda x: [func_1(x[0]), func_2(x[1])], test_array))

print(out)

Prints:

[[11, 3], [11, 3], [12, 4]]

Or using comprehension:

out = [[func_1(x), func_2(y)]  for x, y in test_array]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. It's rather above my level. I'm not familiar with map and lambda. Your one-liner answer looks simple, yet complex :)
@user3848207 I added the list comprehension, it's easier to do it with it
3

Use a list comprehension:

>>> [[func_1(x0), func_2(x1)] for x0, x1 in test_array]
[[11, 3], [11, 3], [12, 4]]

Or without unpacking: [[func_1(x[0]), func_2(x[1])] for x in test_array]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.