7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

itertoolsを用いて順列, 組合せを作ろう

Posted at

#環境
python3.6.3
macOS version10.14.

#itertools
python で組合せについて調べていたら, itertoolsモジュールにたどり着きました. イテレーションに関する関数が多く用意されているようなので, いくつか試してみます.
import itertools と記述することで使うことができます.

#順列
itertools.permutations(iterable, r)
rで一度に取り出す要素数を指定する.
順列はタプルで格納される.

tmp = ['a', 'b', 'c',]
print(list(itertools.permutations(tmp,2)))
#[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

#組合せ(重複なし)
itertools.combinations(iterable, r)
rで一度に取り出す要素数を指定する.
組合せはタプルで格納される.

tmp = ['a', 'b', 'c',]
print(list(itertools.combinations(tmp,2)))
#[('a', 'b'), ('a', 'c'), ('b', 'c')]

#組合せ(重複あり)
itertools.combinations_with_replacement(iterable,r)
rで一度に取り出す要素数を指定する.
組合せはタプルで格納される.

tmp = ['a', 'b', 'c',]
print(list(itertools.combinations_with_replacement(tmp,2)))
#[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

#無限イテレータ
####count(start, [step])
startからstep飛ばしの整数を無限に返す.

itr = itertools.count(5,3)
for i in itr:
    print(i, end=' ')
    if i >25:
        break
#5 8 11 14 17 20 23 26

####itertools.cycle(iterable)
引数に与えられたイテレータの要素を無限に返す

tmp = ['a', 'b', 'c']
itr = itertools.cycle(tmp)
for i, x in enumerate(itr):
    print(x, end=' ')
    if i >10:
        break
#a b c a b c a b c a b c

####itertools.repeat(object, times)
objectを指定回数返す

itr = itertools.repeat('Hello',3)
for i in itr:
    print(i, end=" ")
#Hello Hello Hello
7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?