learner123 - 1 year ago 86

Python Question

Here is the question:

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

Required output: any value

`> 1`

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**