ふと忘れてしまう、pythonの内包表記をまとめてみました
この記事の目次
リスト内包表記
シンプルな使い方
# 内包表記なし
t = (1, 2, 3, 4, 5)
r = []
for i in t:
r.append(i)
print("r =",r)
# r = [1, 2, 3, 4, 5]
#############
# 内包表記あり
r = [i for i in t]
print("r =",r)
# r = [1, 2, 3, 4, 5]
ifを使う場合
# 内包表記なし
t = (1, 2, 3, 4, 5)
r = []
for i in t:
if i % 2 == 0:
r.append(i)
print("r =",r)
# r = [2, 4]
#############
# 内包表記あり
t = (1, 2, 3, 4, 5)
r = [i for i in t if i % 2 == 0]
print("r =",r)
# r = [2, 4]
forを2つ使う場合
# 内包表記なし
t = (1, 2, 3, 4, 5)
t2 = (5, 6, 7, 8, 9, 10)
r = []
for i in t:
for j in t2:
r.append(i * j)
print("r =",r)
# r = [5, 6, 7, 8, 9, 10, 10, 12, 14, 16, 18, 20, 15, 18, 21, 24, 27, 30, 20, 24, 28, 32, 36, 40, 25, 30, 35, 40, 45, 50]
#############
# 内包表記あり
t = (1, 2, 3, 4, 5)
t2 = (5, 6, 7, 8, 9, 10)
r = [i * j for i in t for j in t2]
print("r =",r)
# r = [5, 6, 7, 8, 9, 10, 10, 12, 14, 16, 18, 20, 15, 18, 21, 24, 27, 30, 20, 24, 28, 32, 36, 40, 25, 30, 35, 40, 45, 50]
辞書内包表記
# 内包表記なし
w = ['mon', 'tue', 'wed']
f = ['coffee', 'milk', 'water']
d = {}
for x, y in zip(w, f): # zipは順番に取り出す関数
d[x] = y
print(d)
# {'mon': 'coffee', 'tue': 'milk', 'wed': 'water'}
#############
# 内包表記あり
w = ['mon', 'tue', 'wed']
f = ['coffee', 'milk', 'water']
d = {x: y for x, y in zip(w, f)}
print(d)
# {'mon': 'coffee', 'tue': 'milk', 'wed': 'water'}
集合内包表記
# 内包表記なし
s = set()
for i in range(10):
s.add(i) # set型(集合)にappendは使えない
print(s)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
#############
# 内包表記あり
s = {i for i in range(10)}
print(s)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
# ifを入れる場合
s = set()
for i in range(10):
if i % 2 ==0:
s.add(i)
print(s)
ジェネレーター内包表記
# 内包表記なし
def g():
for i in range(5):
yield i
g = g ()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#<class 'generator'>
#0
#1
#2
#3
#4
#############
# 内包表記あり
g = ( i for i in range(5)) # 一見タプルになりそうだがならない
print(type(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#<class 'generator'>
#0
#1
#2
#3
#4
# ifを入れることもできる
g = ( i for i in range(5) if i % 2 == 0)
print(type(g))
print(next(g))
print(next(g))
print(next(g))
#<class 'generator'>
#0
#2
#4
|
---|
コメントを残す