LoginSignup
3
0

More than 1 year has passed since last update.

for文を1行でスマートに書きたい!

Posted at

はじめに

最近つよつよエンジニアの方のコードを見る機会が多々あり、そのコードの中にfor文が1行で書かれていた。
これまで難しそうと思って避けてきたがレベルアップのためだと思い、調べてみたら意外にも簡単で便利だった。

Q : どのようなときに使える?

 A : イテラブルに値を代入するとき

イテラブル(繰り返し可能な)なデータであるリストや辞書などに利用することができ、この表記法を内包表記という。

リストの場合

# a = [代入したい値 for 代入したい値 in イテラブルオブジェクト (if文)]

abc_list = [0, 1, 2, 3, 4]
a = [i for i in abc_list]

"""
a = []
for i in abc_list:
    a.append(i)
"""
print(a)

b = [j for j in abc_list if j > 2] # 2より大きい値のみbに代入されている

"""
b = []
for j in abc_list:
    if j > 2:
        b.append(j)
"""
print(b)

c = [k + 2 for k in abc_list] # abc_listの各要素に2が加算された値がcに代入されている

"""
c = []
for k in abc_list:
    c.append(k + 2)
"""
print(c)
[0, 1, 2, 3, 4]
[3, 4]

辞書の場合

#a = {キーに代入したい値: 値に代入したい値 for キーに代入したい値, 値に代入したい値 in イテラブルオブジェクト}

fruit = ["apple", "banana", "peach", "greep", "orange"]
a = {key: 0 for key in fruit}

"""
a = {}
for key in fruit:
    a[i] = 0
"""

print(a)

good_or_bad = ["good", "bad", "good", "good", "bad"]
b = {key: emotion for key, emotion in zip(fruit, good_or_bad)} # キーにfruit配列が、emotionにgood_or_bad配列が代入されている

"""
b = {}
for key, emotion in zip(fruit, good_or_bad):
    b[i] = j
"""
print(b)

good_or_bad = ["good", "bad", "good", "good", "bad"]
c = {key: emotion for key, emotion in zip(fruit, good_or_bad) if emotion == "good"} 
 # good_or_badがgoodの位置にあるfruitの要素のみcに代入

"""
c = {}
for key, emotion in zip(fruit, good_or_bad):
    if emotion == "good":
        c[key] = emotion
"""
print(c)
{'apple': 0, 'banana': 0, 'peach': 0, 'greep': 0, 'orange': 0}
{'apple': 'good', 'banana': 'bad', 'peach': 'good', 'grape': 'good', 'orange': 'bad'}
{'apple': 'good', 'peach': 'good', 'grape': 'good'}

zip関数は辞書にキーと値の二つを代入することができる

3
0
2

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