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
Mizipzor
  • 48,671
  • 21
  • 94
  • 137
nos
  • 18,322
  • 27
  • 89
  • 126
  • possible duplicate of [Nested for loops in Python](http://stackoverflow.com/questions/7164162/nested-for-loops-in-python) – BrenBarn Aug 20 '12 at 04:12
  • it is not a duplicate. The answer based on `numpy.meshgrid()` or similar is not appropriate for the other question. – jfs Aug 20 '12 at 04:21
  • related: [itertools product speed up](http://stackoverflow.com/q/4709510/4279) – jfs Aug 20 '12 at 04:44
  • 1
    Better in what way? Faster? More memory efficient? Prettier? – bchurchill Aug 20 '12 at 05:48

2 Answers2

26
import itertools

for a,b,c in itertools.product(cc1, cc2, cc3):
    print a,b,c
Amber
  • 477,764
  • 81
  • 611
  • 541
7

try this :)

[(c1, c2, c3) for c1 in cc1 for c2 in cc2 for c3 in cc3]
blueiur
  • 1,407
  • 1
  • 11
  • 17