2
3

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 (内包表記)

Last updated at Posted at 2019-06-07

内包表記(コンプリヘンション)について

今回は、内包表記について。

元々、Progate2週程度の理解しかなく現場でのソースがほとんどこの内包表記という書き方で
書かれていて、もう「for文の前についてる変数…なにこれ??」みたいな感じだった。

勉強しなんとなく理解できたので、簡単にまとめていきたいと思う。

内容表記とは

for文でリストを作成していく際、短く簡潔な方法で書くこと。
他にもディクショナリやset型も扱うことができる。

通常の記述方法

例:
下記のdata変数へ1~5までの数値をリストとして代入し、


data = [1, 2, 3, 4, 5]

配列の中身を3倍にする処理をfor文で回しながらnewData変数へ再度、入れ込んでいく

newData = []
for d in data:
  newData.append(d * 3)

# [3, 6, 9, 12, 15]

内容表記での記述

上記3行で表してた処理を1行で簡潔に記述すると以下のようになる。

newData = [d * 3 for d in data]

# [3, 6, 9, 12, 15]

if文を使った条件式

入れ子構造にして、if文で条件をつける場合も可能。

for d in data:
   if  d % 2 ==0:
      newData.append(d)
      #[2, 4]

上記の記述を内包表記で記述すると、以下のようになる。

newData = [d for d in data if d % 2 == 0]
# [2, 4]
2
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?