UniMss
UniMss

Reputation: 27

How can I loop over true values in Python

I have a boolean array in python and I want to do a calculation on the cells where the value is 'true'. Currently I am using a nested for loop to go trough all the cells to find the cells with the true values. However, running the program takes a lot of time. I was wondering wether there is a faster way to do this?

for i in range (0,latstep):  
    for j in range (0,lonstep):     
        if coastline[i,j] == True:
        ... 

Thanks for your help!

Upvotes: 1

Views: 1156

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can use nested list comprehensions, each comprehension is slightly faster than a generic for-loop on smaller input sizes:

final_list = [[foo(b) for b in i if b] for i in coastline]

Upvotes: 0

Jarvis Cochrane
Jarvis Cochrane

Reputation: 101

You might consider using concurrent.map() or similar to process the array elements in parallel. Always assuming there aren't dependencies between the elements.

Another possibility is maintaining a list of the 'true' values when you initially calculate them:

coastlineCache = []

c = foo()
coastline[i][j] = c

if (c):
    coastlineCache.append(c)

// later

for (c in coastlineCache):
    process_true_item(c)

If, as you've alluded to above, you need the array indices, cache them as a tuple:

coastlineCache = []

c = foo()
coastline[i][j] = c
if (c):
    coastlineCache.append((i, j))

// later

for (c in coastlineCache):
    process_true_item(c[0], c[1]) # e.g. (i, j)

Upvotes: 2

Related Questions