Avoid multiple loops in Python


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.

Sample code before change


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


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

Method 1: Use itertools.product ()

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


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)

Method 2: Use comprehensions

Nested comprehensions are also available.


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)

Bonus: For Ruby


years = Array(2010..2012)
integers = Array(1..2)
chars = Array('a'..'c')

years.product(integers, chars) { |year, i, char| puts("#{year} #{i} #{char}") }


[^ 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

Avoid multiple loops in Python
Avoid nested loops in PHP and Python
Multiple regression expressions in Python
Avoid KeyError in python dictionary
Prohibit multiple launches in python
[Python] Show multiple windows in Tkinter
Statistical test (multiple test) in Python: scikit_posthocs
Delete multiple elements in python list
Handle multiple python versions in one jupyter
When specifying multiple keys in python sort
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Send email to multiple recipients in Python (Python 3)
Epoch in Python
Discord in Python
Decorator to avoid UnicodeEncodeError in Python 3 print ()
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
Process multiple lists with for in Python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Get multiple maximum keys in Python dictionary type
[Python] Dealing with multiple call errors in ray.init
Sorted list in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
About Python for loops