リスト内包表記の記法
[ 式 for 変数 in シーケンス ]
# 面積を求める
squares = [ i ** 2 for i in range(5)]
print(squares)
>>[0, 1, 4, 9, 16]# 奇数と偶数
odds = [ i for i in range(10) if i % 2 == 1]
even = [ i for i in range(10) if i % 2 == 0]
print(odds)
print(even)
>>[1, 3, 5, 7, 9]
>>[0, 2, 4, 6, 8]# 奇数or偶数
odd_even = ['odd' if i % 2 == 1 else 'even' for i in range(10)]
print(odd_even)
>>['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']# ネスト可
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flat = [x for row in matrix for x in row] # ← 順番逆にするんだ
print(flat)
>>[1, 2, 3, 4, 5, 6, 7, 8, 9]# 複数の変数も利用可
cells = [(row, col) for row in range(3) for col in range(2)]
print(cells)
>>[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]ループより内包表記が便利
- 前後を入れ替えることで並びが変わる
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]
>>> tshirts
[('black', 'S'),
('black', 'M'),
('black', 'L'),
('white', 'S'),
('white', 'M'),
('white', 'L')]
tshirts = [(color, size) for size in sizes for color in colors]
>>>tshirts
[('black', 'S'),
('white', 'S'),
('black', 'M'),
('white', 'M'),
('black', 'L'),
('white', 'L')]