Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I change this one line for loop to normal for loop?

This is a general question that I was not to able to understand.

If I have this:

somelist = [[a for a, b in zip(X, y) if b == c] for c in np.unique(y)]

How can I write this as normal multiline for loop? I never seem to get it right.

EDIT: So far I've tried this:

somelist = []
for c in np.unique(y):
    for x, t in zip(X, y):
        if t == c:
            separated.append(x)

But I wasn't sure if this was right because I wasn't getting an expected result in some other part of my code.

like image 245
Subbu Dantu Avatar asked Jan 25 '26 22:01

Subbu Dantu


2 Answers

Let me know if this works: evaluate the outer list comprehension first for the outer loop. then evaluate the inner list comprehension.

somelist=[]
for c in np.unique(y):
    ans=[]
    for a,b in zip(X,y):
        if b==c:
            ans.append(a)
    somelist.append(ans)
like image 114
Akshay Apte Avatar answered Jan 28 '26 15:01

Akshay Apte


To flat a nested comprehension out, follow these steps:

  1. First create an empty container: somelist = []
  2. If the comprehension has an if clause, put it right after the for
  3. Then, flat the nested comprehensions out, starting with the innermost

The inner comprehension is:

row = []
for a, b in zip(X, y):
    if b == c:
        row.append(a)

Then, somelist is nothing more than [row for c in np.unique(y)], where row depends on several factors. This one is equivalent to:

somelist = []
for c in np.unique(y):
    somelist.append(row)

So the complete version is:

somelist = []
for c in np.unique(y):
    row = []
    for a, b in zip(X, y):
        if b == c:
        row.append(a)
    c.append(row)
like image 40
Right leg Avatar answered Jan 28 '26 13:01

Right leg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!