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 5 years have passed since last update.

Pythonの内包表記について

0
Last updated at Posted at 2019-09-26

目的

いまだにPythonの内包表記がいまいち理解できていないのでざっくり再確認

内包表記とは

Pythonにてリストをforを用いて生成する方法
1行で書ける&早いので便利

基本の書き方

array = [x for x in イテラブル]

xが2回出る
1回目のxはfor内容を受け取る変数のような認識でいいっぽい
2回目のxは通常のforと同じくリストを順繰りに見た値が入る
リストはスライスも可能

※コメントにより訂正
forの前には式を指定でき、forによって作られた値をさらに演算してリスト化可能
なので以下のようにすべての値を2倍してリスト化などもできる

array = [2*x for x in イテラブル]

※コメントにより訂正
forで走査するのはリストと言うよりイテラブルなオブジェクト(連続するデータ列)

条件指定

ifで条件に合致したもののみリストにすることができる。

array = [x for x in イテラブル if 条件]

実際にやってみる

適当なリストから偶数だけ抜き出してみる
偶数を2倍したものもリスト化してみる

array = [1,3,4,6,7,8,9,0,23]
array2 = [x for x in array if x%2==0]
array3 = [2*x for x in array if x%2==0]
print(array2)
# >>[4, 6, 8, 0]
print(array3)
# >>[8, 12, 16, 0]

参考文献

pythonの内包表記を少し詳しく
https://qiita.com/y__sama/items/a2c458de97c4aa5a98e7

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