LoginSignup
3
3

More than 5 years have passed since last update.

Python の yield from をつかって flatten する

Last updated at Posted at 2015-09-01

yield はわかったのですが yield from ってなんだよということで調べて generator の評価をうけとる仕組みかなという理解になりました

その理解で flatten 書いてみた

def flatten(x):
    if hasattr(x, '__iter__') and not isinstance(x, str):
        for y in x:
            yield from flatten(y)
    else:
        yield x

この yield fromyield にすると 単に generator が返ってくるのでまあ理解あってるかなとなる

In : ls = [1,2,3,[4,5],[6,[7,8,[9,10,11],12]]]

In : list(flatten(ls))
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

つかいこなせるかというとよくわからない

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