1
1

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_itertoolsを使うワタッコ、MORECCO(自分用メモ)

1
Posted at

基本の形

基本の形
from more_itertools import pairwise
from more_itertools import windowed

こんな感じで、import の後ろを書き換えて使うっぽい

pairwise:隣り合う要素を取る

入力
from more_itertools import pairwise

a = [1, 4, 9, 16]
for x, y in pairwise(a):
    print(x, y)
出力
1 4
4 9
9 16

隣同士を出してくれる。別になくても良いけど便利かもしれん

windowed:スライドした値を出す

入力
from more_itertools import windowed

a = [1, 2, 3, 4, 5]
for w in windowed(a, 3):
    print(w)
出力
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)

指定した数に合わせてスライドしたやつを作ってくれる、ちょっと便利かもしれない。

chunked:配列をK個ずつ切る

入力
from more_itertools import chunked

a = [1,2,3,4,5,6,7]
print(list(chunked(a, 3)))
出力
[(1,2,3), (4,5,6), (7,)]

指定した値で区切ったやつを作ってくれる

un_length.encode:ランレングス圧縮

入力
from more_itertools import run_length

s = "aaabbbbcc"
print(list(run_length.encode(s)))
出力
[('a', 3), ('b', 4), ('c', 2)]

distinct_permutations:重複なし順列

入力
from more_itertools import distinct_permutations

a = [1,1,2]
print(list(distinct_permutations(a)))
出力
[(1,1,2), (1,2,1), (2,1,1)]

set(permutations()) より速くて綺麗ってchatGPTが言ってるんですけど本当ですか?

powerset:部分集合

入力
from more_itertools import powerset

a = [1,2,3]
print(list(powerset(a)))
出力
[(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]

N ≤ 20くらいのbit全探索ができるやつ

split_at / split_when:条件で分割

入力
from more_itertools import split_at

a = [1,2,0,3,4,0,5]
print(list(split_at(a, lambda x: x == 0)))
出力
[[1,2], [3,4], [5]]

区切り文字で分割(この場合は0)だけどいるのかなこれ

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?