I previously posted a Ruby article called Avoid multiple loops with Array # product. This article uses Array # product to turn multiple loops into a single loop [^ 1] ] Introducing the method. I've been personally into Python these days, so I tried to find out how to write in this language.

`python`

```
for year in range(2010, 2013):
for i in range(1, 3):
for char in ('a', 'b', 'c'):
print(year, i, char)
```

`stdout`

```
2010 1 a
2010 1 b
2010 1 c
2010 2 a
2010 2 b
2010 2 c
2011 1 a
2011 1 b
2011 1 c
2011 2 a
2011 2 b
2011 2 c
2012 1 a
2012 1 b
2012 1 c
2012 2 a
2012 2 b
2012 2 c
```

To find the Cartesian product (direct product) of itertools.product () in Python as well as Ruby's Array # product. There is a function of.

`python`

```
from itertools import product
years = range(2010, 2013)
integers = range(1, 3)
chars = ('a', 'b', 'c')
for year, i, char in product(years, integers, chars):
print(year, i, char)
```

Nested comprehensions are also available.

`python`

```
years = range(2010, 2013)
integers = range(1, 3)
chars = ('a', 'b', 'c')
combinations = [(year, i, char)
for year in years
for i in integers
for char in chars]
for year, i, char in combinations:
print(year, i, char)
```

`ruby`

```
years = Array(2010..2012)
integers = Array(1..2)
chars = Array('a'..'c')
years.product(integers, chars) { |year, i, char| puts("#{year} #{i} #{char}") }
```

- Jedi style / Python comprehension
- I referred to the nested inclusion notation.

[^ 1]: It's just an appearance, it's about going from multiple to one indentation with loop syntax. It does not reduce the number of internal loops or the amount of calculation.

Recommended Posts