lundi 27 juin 2016

Can you use if-else statement inside braces for an array in Python?

I'm wondering if there is a nice way to use an if-else statement inside braces of an array in Python to assign values. What I would like is something like:

A = #some 2D array of length m by n, already initialized
A = np.float64(A)
val = someValue #any number, pick a number

A = [[val for j in range(n) if A[i][j] < val, else A[i][j]=A[i][j]] for i in range(m)]

Is there a nice way to do this? Alternatively, if numpy has a faster way to compute this that would be equally as good, if not better.

The longer way to do what I am trying to achieve would be something like

for i in range(m):
    for j in range(n):
        if A[i][j] < val:
            A[i][j] = val

The desired output is to set any values below a threshold to that threshold. I can do simpler if-statements with a 1D array such as

myArray = [otherArray[i] for i in range(theRange) if otherArray[i]>=value and otherArray[i]<=anotherValue]

This 1D example is not what I want. It's just an example of the type of coding block I'm looking for. It seems to be quicker at processing against the traditional if-else statements.

Aucun commentaire:

Enregistrer un commentaire