learner123 learner123 - 4 months ago 6
Python Question

Inline expression using for and if loops

Here is the question:

input = array([ 0. , 0.5, 1. , 1.5])


Required output: any value
> 1
should be set to
1


array([ 0. , 0.5, 1. , 1])


My current program

import numpy as np

input = np.arange(0,2,0.5);#array([ 0. , 0.5, 1. , 1.5])

for i in np.arange(0, np.size(input)):
if input[i] > 1:
input[i] = 1


What is the short form for this simple operation:

dummy3 =[if i> 1: xxxxxx , for i in input]
or
output = [if (for i in input) > 1: return 1 ]

Answer
output = [1 if i > 1 else i for i in input]

It's called list comprehension

This create a new list that populate (conceptually) like this:

output = []
for i in input:
    if i > 1:
        output.append(1)
    else:
        output.append(i)

As mentioned in the comments, when you use numpy and want to change the original array you can do:

input[input>1]=1
Comments