0
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 than 1 year has passed since last update.

Python: ラムダ式で yield を使う

Last updated at Posted at 2022-12-11

まずは普通のyieldの簡単な使いかたです。

>>> def g():
    yield 0
    yield 1
    return

>>> a = g()
>>> next(a)
0
>>> next(a)
1
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

こんな風にするとラムダ式でも yield できます。

>>> g = lambda : (
    (yield 0)
    , (yield 1)
    )
>>> a = g()
>>> next(a)
0
>>> next(a)
1
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration: (None, None)

yield from も使えます。

>>> g = lambda : (yield from [0,1])
>>> a = g()
>>> next(a)
0
>>> next(a)
1
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

ループは使えないので再帰などを使って工夫する必要があります。カウンタの例。

>>> count = lambda n : (
    (yield n)
    , (yield from count(n+1))
    )
>>> a = count(1)
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
4

いたずらに変わった書き方をする必要はありませんが、主に他言語との連携、他言語からの類推でラムダ式をもっと有効に使いたいという潜在需要はあると思います。自己責任でお使いください。

0
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
0
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?