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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With