1
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 1 year has passed since last update.

PythonのList Comprehension (listcomps) の使い方

Posted at

Pythonでlist型の新規作成には、listcompsを使用できる。

word = 'ABC'

# listcomps 可読性が高い
codes = [ord(c) for c in word]
# [65, 66, 67]

# 同じことをfor文で繰り返し処理の場合
for c in word:
  codes.append(ord(c))

また、下記のようにmapとfilterを使用すれば、listcompsと同じ処理を実現可能。
可読性はやはりlistcompsが上だと感じる。(個人的にそう感じる。)

# listcomps
codes = [ord(c) for c in word if ord(c) > 127]
# map と filter
codes = list(filter(lambda c: c > 127, map(ord, word)))

listcompsは複数のfor文も使用できるので、便利。

clothes = [(color, size) for color in colors for size in sizes]
# [('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]
1
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
1
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?