itertoolモジュールのpermutations
関数を使うと、簡単に順列を作ることができる。
permutationはなかなか見慣れない英単語だが、「順列、交換、置換、並べ換え」といった意味がある。パッと思い出せるぐらいには覚えておくと良さそう。
今回はpermutations
関数を実行し、使い方や動きを確認する。
前提条件
Google Colab上で確認
このときのバージョンはPython 3.7.12
実行
エンジニアに親しみのあるプログラミング言語についてのランキングを作成する例とした。
permutations
関数はiterableオブジェクトを引数に取る。そのため、language変数に3つの言語名を入れたリストを渡している。
これだけで順列を作成できる。
language = ['Python', 'Ruby', 'Go'] import itertools list(itertools.permutations(language))
[('Python', 'Ruby', 'Go'), ('Python', 'Go', 'Ruby'), ('Ruby', 'Python', 'Go'), ('Ruby', 'Go', 'Python'), ('Go', 'Python', 'Ruby'), ('Go', 'Ruby', 'Python')]
テーブル形式に変換すると、下記と同じデータになっている。
1位 | 2位 | 3位 |
---|---|---|
Python | Ruby | Go |
Python | Go | Ruby |
Ruby | Python | Go |
Ruby | Go | Python |
Go | Python | Ruby |
Go | Ruby | Python |
permutations
関数の2つめの引数に、これは取り出したい個数を入力する。今回は2と入力する。
指定することで ['Python', 'Ruby', 'Go']
の3つの中から2つだけ取り出したいことを実現することができる。
language = ['Python', 'Ruby', 'Go'] import itertools list(itertools.permutations(language,2))
[('Python', 'Ruby'), ('Python', 'Go'), ('Ruby', 'Python'), ('Ruby', 'Go'), ('Go', 'Python'), ('Go', 'Ruby')]
1位 | 2位 |
---|---|
Python | Ruby |
Python | Go |
Ruby | Python |
Ruby | Go |
Go | Python |
Go | Ruby |
ちなみに、元の要素より大きい数を指定すると、空のオブジェクトが返る。
空のリストが表示されているのは、list
関数で囲んでいるからである。
language = ['Python', 'Ruby', 'Go'] import itertools list(itertools.permutations(language,4))
[]