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?

[Python]内包表記

Posted at

内包表記とは

内包表記を使うとりすと、辞書、集合などを生成するときより簡潔に、そして早く作成できます。

まずは、従来の方式であるfor文を使って0から9までの数を2で乗じた結果をリストに保存してみましょう。

a = []
for i in range(10):
    a.append(i*2)

a    # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

今度は内包表記を使ってリストを生成します。

a = [i*2 for i in range(10)]

a    # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

そして、if文を使ってフィルタリングもできます。

a = [i*2 for i in range(10) if i < 5]

a    # [0, 2, 4, 6, 8]

ネストしたリスト

ネストしたリストも内包表記で生成できます。

shirts = ['long', 'short']
pants = ['long', 'short']

clothes = [(shirt, pant) for shirt in shirts for pant in pants]
clothes # [('long', 'long'), ('long', 'short'), ('short', 'long'), ('short', 'short')]

でも、このようなコードは可読性が下がるため、普通のfor文を使う方がよいと思います。


集合

集合も内包表記で生成できます。

{i*2 for i in range(10) #{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

辞書

辞書も内包表記で生成できます。

{i: i*2 for i in range(5)} # {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
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?