How to write conditional branching in the contents of an array when the array is used as an argument in the Python function.

Asked 2 years ago, Updated 2 years ago, 33 views

I would like to use Python 3.6 to create a function that changes the output according to the contents of the given array.

input_data=[1,2,3]
defequ(x):
Value for each element of ifx > 2:
    return x +3
else:
    return x+1

Expected output for equ(input_data): [2,3,6]

How do we create these functions?
If not, how can I code efficiently?

Thank you for your cooperation

python python3

2022-09-30 15:34

1 Answers

Spinning each element of the array with for would be good.

input_data=[1,2,3]


defequ(x):
    result = [ ]
    for e in x:
        if > 2:
            result.append(e+3)
        else:
            result.append(e+1)
    return result
print(equ(input_data))

A function that receives each element of the array, not the array itself, can be more concise.

input_data=[1,2,3]

print(list(map(
    lambdax: x +3 if x > 2 else x +1,
    input_data,
)))


2022-09-30 15:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.