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?

More than 3 years have passed since last update.

備忘録:多重ネストしたループの内包表記

Last updated at Posted at 2020-02-27

for文がネストした内包表記を書こうとしたら一発でできなかったので忘れないようにメモ

以下のような辞書型を二次元のリストに変換する処理をやりたかった

> # これを
> d1 = {'a': {'aa': (1, 3), 'ab': (5, 7)}, 'b': {'ba': (2, 4), 'bb': (6, 8)}}

> # こうしたい
> _d1 = [('a', 'aa', 1, 3), ('a', 'ab', 5, 7), ('b', 'ba', 2, 4), ('b', 'bb', 6, 8)]

for文を内包表記で書くときは_forの前方に中身がくる_と安直に覚えていたので、内部のfor文を外側のfor文の前方に書いた。

> [(k, _k, vals[0], vals[1]) for _k, vals in obj.items() for k, obj in d1.items()]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'obj' is not defined

name 'obj' is not defined

ネストしたループは後方に書くのが正解

> [(k, _k, vals[0], vals[1]) for k, obj in d1.items() for _k, vals in obj.items()]
[('a', 'aa', 1, 3), ('a', 'ab', 5, 7), ('b', 'ba', 2, 4), ('b', 'bb', 6, 8)]
0
0
2

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?