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

メモ: リスト内包表記

Posted at

リスト内包表記

めちゃくちゃ使うのでメモ。例えば n^2 の数列を作りたい時

python3
>>> l = [i**2 for i in range(6)]
>>> l 
[0, 1, 4, 9, 16, 25]

このように f(x) for x in <イテレータ>] とすれば f(x) のリストを返してくれます。

if を併用

こう書けば条件を満たす要素のみに絞れます

python3
>>> l = [i**2 for i in range(6) if i%2 == 0] // i  偶数の場合のみの i**2 を返す
>>> l 
[0, 4, 16]

if else を併用

条件を満たすかどうかで値を変化させたい時は if else を使ってこんな感じにします

python3
>>> l = [i**2 if i%2 == 0 else 'odd' for i in range(6)]
>>> l 
[0, 'odd', 4, 'odd', 16, 'odd']

ネスト

ネストすることも可能

python3
>>> l = [(i, j) for i in range(3) for j in ['a','b','c']]
>>> l
[(0, 'a'),
 (0, 'b'),
 (0, 'c'),
 (1, 'a'),
 (1, 'b'),
 (1, 'c'),
 (2, 'a'),
 (2, 'b'),
 (2, 'c')]
1
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
1
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?