0

I have only recently started working with Python's list comprehensions. I am not comfortable with them. How would I optimise the code below by using list comprehensions?

heatmap_color = []

for r in xrange(len(heatmap)):
    heatmap_color.append([])
    for c in xrange(len(heatmap[r])):
        heatmap_color[r].append(cmap.to_rgba(heatmap[r][c], alpha=0.5, bytes=True))

What this code does is create a 2D array (representing a colour image's pixel values). The last line maps each one of the existing grayscale pixels in heatmap to a colour with an alpha channel = 0.5 so that these can be entered in the corresponding entry in the heatmap_color array.

Currently it takes just under 30 seconds to run. I would like to reduce this time as much as possible.

Thank you!

1 Answer 1

4

Nest the loops:

heatmap_color = [[cmap.to_rgba(r, alpha=0.5, bytes=True) for r in c] for c in heatmap]

Note that we don't need to use indices (generated by xrange()); loop directly over the lists instead.

You could use map() and functools.partial() here too to speed things up a little more still:

from functools import partial
heatmap_rgba = partial(cmap.to_rgba, alpha=0.5, bytes=True)
heatmap_color = [map(heatmap_rgba, c) for c in heatmap]

or even:

from functools import partial
heatmap_rgba = partial(cmap.to_rgba, alpha=0.5, bytes=True)
heatmap_per_list = partial(map, heatmap_rgba)
heatmap_color = map(heatmap_per_list, heatmap)

because map() can be faster than list comprehensions, especially when used with functools.partial to avoid the extra stack-push a lambda would require.

Sign up to request clarification or add additional context in comments.

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.