pistal
pistal

Reputation: 2456

Convert nested loops and conditions to a list comprehension

Is there a way for list comprehending this condition set.

clamp_sel = list()
for i in range(0, len(clamp_normalized)):
        for j in range(0, len(clamp_normalized[i])):
                if clamp_normalized[i][j][0] < int(max_min_band[index_selec]):
                        clamp_sel.append(int(clamp_normalized[i][j][0]))

If it is single dimension list, I could set the condition in this way.

norm_sel = [i for i in normalize_data if i[0] > max_min_band[index_selec]]

Thanks

Upvotes: 1

Views: 1760

Answers (2)

Bas Swinckels
Bas Swinckels

Reputation: 18488

This should translate directly into a list-comprehension:

clamp_sel = [int(clamp_normalized[i][j][0])
    for i in range(0, len(clamp_normalized))
    for j in range(0, len(clamp_normalized[i]))
    if clamp_normalized[i][j][0] < int(max_min_band[index_selec])]

The general rule is (see the manual) that you should write the list-comprehension in exactly the same order as you would do with a series of nested for loops and if-statements. The only thing you change is to replace the final xx.append(yy) with just yy at the front of the list comprehension. Also note that this is essentially one long expression that you could write on an extremely long line. Because of the enclosing [], you can divide this expression over multiple lines, with arbitrary indentation.

If the list-comprehension is more pythonic than the original is a question of taste. In this case, the nesting is straightforward, so I would personally go for the list-comprehension. If it gets more complex, stick to the for-loops.

As thefourtheye shows, this example can be further simplified by replacing the use of range() with a direct iteration over your lists.

Upvotes: 5

thefourtheye
thefourtheye

Reputation: 239483

If clamp_normalized is a list of lists, you can iterate without using range, unless you need the index.

clamp_sel  = [j[0]
                  for i in clamp_normalized
                  for j in i
                  if j[0] < int(max_min_band[index_selec])]

Upvotes: 6

Related Questions