0
0

More than 3 years have passed since last update.

[Python] リスト内包表記

Last updated at Posted at 2021-03-15

概要

1: リスト内包表記とは
2: リスト内包表記の使い方①(基本型)
3: リスト内包表記の使い方②(基本形+if文)

最近、リスト内包表記の使用頻度が増えてきて、なぜ使用した方が良いかを実感できたため、備忘録として記載。

検証環境

OS:18.04.5 LTS
Python:3.6.9

1: リスト内包表記とは

  • for文などの反復処理を比較的シンプルに書くことのできる記法である。
  • for文を使用してループ処理するよりも、実行速度が早い
  • 関数型言語の記法 ※ Python言語は、オブジェクト指向PGと関数型PGの両面の特徴を持つ

2: リスト内包表記の使い方①(基本型)

基本の型

[  for 繰り返し変数 in シーケンス ] 

例1: 文字列(string型)で格納されているリストを数値(int型)に変換する


# データ
point_list = [ '80', '100', '20', '30', '40' ]

# 実行
point_list = [int(i) for i in point_list]

# 結果
[80, 100, 20, 30, 40]

例2: 数値(int型)で格納されているリストを文字列(string型)に変換する


# データ
point_list = [ 80, 100, 20, 30, 40 ]

# 実行
point_list = [str(i) for i in point_list]

# 結果
['80', '100', '20', '30', '40']

3: リスト内包表記の使い方②(基本形+if文使用)

  • if文を使用すると、繰り返し変数の判定でTrueのデータのみリストに追加する

# データ
point_list = [ '80', '100', '20', '30', 'AL' ]

# 実行
point_list = [int(i) for i in point_list if i.isdigit()]

# 結果
[80, 100, 20, 30]

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