简体   繁体   中英

Nested loop list comprehension

How do I write the code below in a list comprehension style?

Residual = np.zeros((noRows, noRows))
Dist = np.zeros((noRows, noRows))
for i in range(noRows):
    for j in range(noRows):
        Residual[i][j] = (data[data.columns[2]][i]-data[data.columns[2]][j])**2
        Dist[i][j] = (data[data.columns[0]][i]-data[data.columns[1]][j])**2

We don't have full code, but from what I can see from your snippet, solution should be something like this:

Residual = [(data[data.columns[2]][i]-data[data.columns[2]][j])**2 for i in range(noRows) for j in range(noRows)]
Dist = [(data[data.columns[0]][i]-data[data.columns[1]][j])**2 for i in range(noRows) for j in range(noRows)]

For example:

noRows = 5
l = [i+j for i in range(noRows) for j in range(noRows)]
print(l)

Output will be:

[0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8]
Press any key to continue . . .

In your case the statement will be way more complicated compared to "i+j" operation.... but list comprehension should be right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM