0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python_itertoolsライブラリで使用頻度が高い標準関数10選

Posted at

Python_itertoolsライブラリで使用頻度が高い標準関数10選

  • 用途: 効率的でメモリ効率の良いイテレーションツール。
  • 例: itertools.chain, itertools.product, itertools.combinations
import itertools

使用率が高い関数10選

  1. itertools.chain(*iterables): 複数のイテラブルを連結します。

    from itertools import chain
    combined = chain([1, 2, 3], ['a', 'b', 'c'])
    print(list(combined))
    
  2. itertools.product(*iterables, repeat=1): 繰り返しを含む直積を計算します。

    from itertools import product
    prod = product([1, 2], ['a', 'b'])
    print(list(prod))
    
  3. itertools.permutations(iterable, r=None): 長さrの順列を生成します。

    from itertools import permutations
    perm = permutations([1, 2, 3], 2)
    print(list(perm))
    
  4. itertools.combinations(iterable, r): 長さrの組み合わせを生成します。

    from itertools import combinations
    comb = combinations([1, 2, 3], 2)
    print(list(comb))
    
  5. itertools.combinations_with_replacement(iterable, r): 重複を許可した組み合わせを生成します。

    from itertools import combinations_with_replacement
    comb_wr = combinations_with_replacement([1, 2, 3], 2)
    print(list(comb_wr))
    
  6. itertools.accumulate(iterable, func=operator.add): 累積結果を返します。

    from itertools import accumulate
    import operator
    acc = accumulate([1, 2, 3, 4], operator.mul)
    print(list(acc))
    
  7. itertools.cycle(iterable): イテラブルの要素を無限に繰り返します。

    from itertools import cycle
    cyc = cycle([1, 2, 3])
    for i, value in zip(range(6), cyc):
        print(value)
    
  8. itertools.repeat(object, times=None): オブジェクトを指定回数または無限に繰り返します。

    from itertools import repeat
    rep = repeat('A', 3)
    print(list(rep))
    
  9. itertools.islice(iterable, start, stop, step=1): イテラブルの一部分をスライスします。

    from itertools import islice
    sliced = islice(range(10), 2, 8, 2)
    print(list(sliced))
    
  10. itertools.groupby(iterable, key=None): 連続する同じキーの要素をグループ化します。

    from itertools import groupby
    data = sorted([('A', 1), ('B', 2), ('A', 3), ('B', 4)], key=lambda x: x[0])
    for key, group in groupby(data, key=lambda x: x[0]):
        print(key, list(group))
    
    
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?