Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `[b for a in x for b in a if not b==k]` mean?

I got absolutely stumped at:

indices = numpy.array([b for a in x for b in a if not b==k])

Any pointers on how I should read [b for a in x for b in a if not b==k], in the context of x being a 2D-array of integers and k being an integer? Or parenthesize it to help me understand the precedence of things?

like image 366
Dan Burzo Avatar asked Jan 04 '23 10:01

Dan Burzo


1 Answers

This is equivalent to:

result = []
for a in x:
    for b in a:
        if not b == k:
            result.append(b)
indices = numpy.array(result)

You can read the list comprehension from left to write and turn them into separate for loops.

like image 74
Simeon Visser Avatar answered Jan 14 '23 12:01

Simeon Visser