Velocity Reviews > Quick nested loop syntax?

# Quick nested loop syntax?

Johannes Bauer
Guest
Posts: n/a

 11-19-2008
Hi group,

if I remember correctly, wasn't there a way to quickly iterate through
nested loops? Something like

a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in someoperator(a, b):
print(x, y)

which would print all tuples of
"a", 4
"a", 9
"a", 13
"b", 4
"b", 9
"b", 13
"c", 4
"c", 9
"c", 13

(not nececssarily in that order, of course).

Thanks,
Johannes

--
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
-- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
<48d8bf1d\$0\$7510\$(E-Mail Removed)>

Mark Dickinson
Guest
Posts: n/a

 11-19-2008
On Nov 19, 5:48*pm, Johannes Bauer <(E-Mail Removed)> wrote:
> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like

Python 2.6 has itertools.product:

http://docs.python.org/library/itert...rtools.product

If you don't have Python 2.6 available, then the documentation
above also contains (almost) equivalent Python code that might
work for you.

Mark

Terry Reedy
Guest
Posts: n/a

 11-19-2008
Johannes Bauer wrote:
> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like
>
> a = { "a", "b", "c" }
> b = { 4, 9, 13}
> for (x, y) in someoperator(a, b):
> print(x, y)

from itertools import product
a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in product(a, b):
print(x, y)

alex23
Guest
Posts: n/a

 11-20-2008
On Nov 20, 3:48*am, Johannes Bauer <(E-Mail Removed)> wrote:
> a = { "a", "b", "c" }
> b = { 4, 9, 13}
> for (x, y) in someoperator(a, b):
> * * * * print(x, y)
>
> which would print all tuples of
> "a", 4
> "a", 9
> "a", 13
> "b", 4
> "b", 9
> "b", 13
> "c", 4
> "c", 9
> "c", 13

If you're using a version of Python before 2.6, you could also use a
list comprehension:

>>> show = lambda *args: sys.stdout.write('%s\n' % args)
>>> [show((x,y)) for x in a for y in b]

('a', 4)
('a', 9)
('a', 13)
('b', 4)
('b', 9)
('b', 13)
('c', 4)
('c', 9)
('c', 13)