Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) How to use conditional statements on every element of array using [:] syntax?

If i need to ask a condition on every element of a numpy.ndarray of integers, do I have to use a for loop

for i in range(n):
    if a[i] == 0:
        a[i] = 1   

or can I ask the question using [:] syntax

if a[:] == 0:
    #...

I know the previous is wrong, but is there any way of doing something similar?

like image 304
Juanig Avatar asked Aug 23 '17 20:08

Juanig


1 Answers

You can use the all builtin function to accomplish what your asking:

all(i == 0 for i in a)

Example:

>>> a = [1, 0, 0, 2, 3, 0]
>>> all(i == 0 for i in a)
False

Note however that behinds the scenes, all still uses a for loop. It's just implemented in C:

for (;;) {
    item = iternext(it);
    if (item == NULL)
        break;
    cmp = PyObject_IsTrue(item);
    Py_DECREF(item);
    if (cmp < 0) {
        Py_DECREF(it);
        return NULL;
    }
    if (cmp == 0) {
        Py_DECREF(it);
        Py_RETURN_FALSE;
    }

EDIT: Given your most recent edits, what you probably want instead is to use a list comprehension with the ternary operator:

[1 if  i == 0 else i for i in a]

Example:

>>> a = [1, 0, 0, 2, 3, 0]
>>> [1 if  i == 0 else i for i in a]
[1, 1, 1, 2, 3, 1]
like image 183
Christian Dean Avatar answered Nov 05 '22 18:11

Christian Dean