13

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
4
  • possible duplicate of Nested for loops in Python Commented Aug 20, 2012 at 4:12
  • it is not a duplicate. The answer based on numpy.meshgrid() or similar is not appropriate for the other question. Commented Aug 20, 2012 at 4:21
  • related: itertools product speed up Commented Aug 20, 2012 at 4:44
  • 1
    Better in what way? Faster? More memory efficient? Prettier? Commented Aug 20, 2012 at 5:48

2 Answers 2

28
import itertools

for a,b,c in itertools.product(cc1, cc2, cc3):
    print a,b,c
Sign up to request clarification or add additional context in comments.

2 Comments

Should be : print( (a,b,c)
This is Python 2.
8

try this :)

[(c1, c2, c3) for c1 in cc1 for c2 in cc2 for c3 in cc3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.