概要
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]