内蔵モジュール-itertools(シーケンス、組合せ、生産、重複シーケンス)


  • itertools計算の値はlistを加えて処理を容易にする必要がある
  • 製品(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要素ごとに最大何個書けるか教えてください.
  • [0,1]は選択可能=>(0,0,0)、(1,1,1)
  • >>> 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)]

    並べ替えと組合せ

  • シーケンス:順序が変更されると、他の組合せになります.
  • (1,2,3)=>2シーケンス、=>(1,2)、(2,1)、(1,3)、(3,1)
  • 組合せ:要素が同じであれば、順序が変更されても同じ組合せです.
  • シーヶンス

  • permutations(list, r)フォーマット
  • rはリストから何個抽出するかを示し、製品で使用されるrepeatと混同しないでください
  • >>> 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)フォーマット
  • rはリストから何個抽出するかを示し、製品で使用されるrepeatと混同しないでください
  • (tip)2つの組合せを選択した場合、listをソートした場合に組合せを行うと、組合せ結果のtupleの最初の要素の数が2番目の要素
  • より小さくなる
    >>> 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)]

    生産と繰り返しシーケンス

  • 本番:繰り返しを許可&要素の順序が変更された場合、他のケースとして認識
  • 繰り返しシーケンス:繰り返しを許可&要素の順序が変更されても、同じケース
  • と認識されます.
  • set()を製造中の凡例値に加算し、=>繰り返しシーケンスの値
  • に等しい
    >>> 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

  • Pythonシーケンス、組合せ、product-itertools