Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple for loops

Tags:

python

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
like image 715
nos Avatar asked Aug 20 '12 04:08

nos


People also ask

Can you have multiple for loops in Python?

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.

How do you split two for loops in Python?

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.

How do you do two for loops?

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.

How do nested loops work in Python?

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.


2 Answers

import itertools

for a,b,c in itertools.product(cc1, cc2, cc3):
    print a,b,c
like image 194
Amber Avatar answered Sep 20 '22 16:09

Amber


try this :)

[(c1, c2, c3) for c1 in cc1 for c2 in cc2 for c3 in cc3]
like image 41
blueiur Avatar answered Sep 18 '22 16:09

blueiur