1

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!

6
  • What are the contents of coastline? Commented Dec 4, 2017 at 13:32
  • coastline[i,j] is invalid Commented Dec 4, 2017 at 13:33
  • Possible duplicate of Find indices of a value in 2d matrix Commented Dec 4, 2017 at 13:35
  • Thanks for the fast answer! coastline is a 2d boolean array. On the locations were coastline is True I want to do a calculation with other arrays. Commented Dec 4, 2017 at 13:36
  • @BilltheLizard, yes thanks! I couldn't find that one Commented Dec 4, 2017 at 13:37

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @JarvisCochrane, this is perfect because I need to use this another time further down the code as well!
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.