Nested for Loops Using List Comprehension

Nested For Loops Using List Comprehension

lst = [j + k for j in s1 for k in s2]

or

lst = [(j, k) for j in s1 for k in s2]

if you want tuples.

Like in the question, for j... is the outer loop, for k... is the inner loop.

Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.

To make it more readable, use multiple lines:

lst = [
j + k # result
for j in s1 # for loop
for k in s2 # for loop
# condition
]

Double Iteration in List Comprehension

Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:

[x for b in a for x in b]

to get the desired result, and yes, one current value can be the iterator for the next loop.

How do I write this nested for loop as a list comprehension?

Given that you are using numpy, I suggest you take advantage of the fact that their for loops are written in C, and often optimized. You will still end up stepping through the data, but a lot faster. This approach is called vectorization.

In this case, you seek to make a boolean mask, which arguably simplifies the operation. Keep in mind that the .sum() call in your expression is a red herring: you are actually summing a scalar boolean, which will always give you zero or one.

Here is how you would find points smaller than -1.282 of the sigma in the second dimension:

result = data < -1.282 * stdev_data[:, None, ...]

Alternatively, you could do

result = data < -1.282 * stdev_data.reshape(stdev_data.shape[0], 1, *stdev_data.shape[1:])

or

result = data < -1.282 * np.reshape(stdev_data, stdev_data.shape[:1] + (1,) + stdev_data.shape[1:])

An even easier solution would be to pass keepdims=True to np.std from the very beginning:

result = data < -1.282 * np.std(data, axis=1, keepdims=True)

keepdims=True ensures that the output of std has the shape (12, 1, 282, 375) instead of just (12, 282, 375), so you don't need to re-insert the dimension yourself.

Now if you actually wanted to compute the counts as your question seems to imply, you could just sum the result mask along the second dimension:

counts = result.sum(axis=1)

Finally, to answer your actual question exactly as stated: for loops translate directly into list comprehensions. In your case, that means four fors in the comprehension, in exactly the order you originally had them:

[data[i, j, lat, lon] < -1.282 * stdev_data[i, lat, lon]
for i in range(data.shape[0])
for j in range(data.shape[1])
for lat in range(data.shape[2])
for lon in range(data.shape[3])]

Since comprehensions are surrounded by brackets, you are free to write their contents on separate lines as I've done, although this is of course not required. Notice that the only real differences are that the contents of the append comes first and there are no colons. Also, that red herring sum is gone.

Nested list comprehension not the same as nested for loop

Your list comprehension doesn't do anything as it does not run without i already been defined outside the list comprehension.

To achieve what you want (and yes, this is counter intuitive ) you need to do this:

[j  for i in range(1,5) for j in range(0,i)]

This will yield:

[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]

which is the same order as your nested for loops.

How to frame two for loops in list comprehension python

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

Comprehension on a nested iterables?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

how to convert nested for loops into list comprehension in python

Let's go one step at a time:

Step 1:

new_l=[]
for sublist in f_list:
for subsublist in sublist:
[new_l.append(i) for i in subsublist]

Step 2:

new_l=[]
for sublist in f_list:
[new_l.append(i) for subsublist in sublist for i in subsublist]

Step 3:

new_l = []
[new_l.append(i) for sublist in f_list for subsublist in sublist for i in subsublist]

And finally:

new_l = [i for sublist in f_list for subsublist in sublist for i in subsublist]

You might want to take a look at Flattening an irregular list of lists

How to make a nested list comprehension?

result = [item for row in prices for item in row]
print(result)

How to convert a list comprehension to a nested loop?

 data = [[int(x) for x in list] for list in values] 

this snippet is a list comprehension, to use a for loop you have to do:

data[]
for list in values:
y = []
for x in list:
y.append(int(x))
data.append(y)


Related Topics



Leave a reply



Submit