内蔵モジュール-itertools(シーケンス、組合せ、生産、重複シーケンス)
22993 ワード
製品(Product)
product(string1, string2)
=>len(string 1)*len(string 2)の組合せ数product(list1, list2)
である場合、結合数は=>len(list 1)*len(list 2)product(list, repeat=n)
=>len(list 1)^nの組合せ数repeat=3
要素ごとに最大何個書けるか教えてください.>>> from itertools import prodouct
>>> list(product('ABCD', 'xy'))
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y'), ('D', 'x'), ('D', 'y')]
>>> list(product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
並べ替えと組合せ
シーヶンス
permutations(list, r)
フォーマット>>> from itertools import permutations
>>> list(permutations([1,2,3], 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 정렬안된 list로 combinations하면 정렬안된 순서로 조합 결과가 나오는 것을 알 수 있음
>>> list(permutations([3,1,2], 2))
[(3, 1), (3, 3), (1, 3), (1, 3), (3, 3), (3, 1)]
くみあわせ
combinations(list, r)
フォーマット>>> from itertools import combinations
>>> list(combinations([1,2,3], 2))
[(1, 2), (1, 3), (2, 3)]
# 정렬안된 list로 combinations하면 정렬안된 순서로 조합 결과가 나오는 것을 알 수 있음
>>> list(combinations([3,1,2], 2))
[(3, 1), (3, 2), (1, 2)]
繰り返しシーケンス(組合せwith replacement)
>>> from itertools import combinations_with_replacement
>>> print(list(combinations_with_replacement([1,2,3], 3)))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]
>>> print(list(combinations_with_replacement([3,1,3], 3)))
[(3, 3, 3), (3, 3, 1), (3, 3, 3), (3, 1, 1), (3, 1, 3), (3, 3, 3), (1, 1, 1), (1, 1, 3), (1, 3, 3), (3, 3, 3)]
生産と繰り返しシーケンス
>>> print(list(product([1,2], repeat=2)))
[(1, 1), (1, 2), (2, 1), (2, 2)]
>>> print(list(combinations_with_replacement([1,2], 2)))
[(1, 1), (1, 2), (2, 2)]
References
Reference
この問題について(内蔵モジュール-itertools(シーケンス、組合せ、生産、重複シーケンス)), 我々は、より多くの情報をここで見つけました https://velog.io/@oneofakindscene/작성중-내장모듈-itertools순열-조합-프로덕트テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol