I am wondering if the 3 for loops in the following code can be written in a better way:
Nc = 10 # number of points for (0, pi)
cc1 = linspace(0,pi,Nc)
cc2 = linspace(0,pi/2,Nc/2)
cc3 = linspace(0,pi/2,Nc/2)
for c1 in cc1:
for c2 in cc2:
for c3 in cc3:
print c1,c2,c3
Nested For Loops Loops can be nested in Python, as they can with other programming languages. The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion.
Another way of breaking out of multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop.
If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } Here, we are using a for loop inside another for loop.
Answer 1: A nested loop refers to a loop within a loop, an inner loop within the body of an outer one. Further, the first pass of the outer loop will trigger the inner loop, which will execute to completion. After that, the second pass of the outer loop will trigger the inner loop again.
import itertools
for a,b,c in itertools.product(cc1, cc2, cc3):
print a,b,c
try this :)
[(c1, c2, c3) for c1 in cc1 for c2 in cc2 for c3 in cc3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With