内包表記のパターンと従来のコードの比較

リスト内包表記

①繰り返しが1回
squares = [x**2 for x in [1, 2, 3, 4]]
 

・従来の方法
squares = []
for x in [1, 2, 3, 4]:
    squares.append(x**2)


②繰り返しが2回
combinations = [(x, y) for x in [1, 2] for y in [3, 4]]

従来の方法:
combinations = []
for x in [1, 2]:
    for y in [3, 4]:
        combinations.append((x, y))


③繰り返しが1回 + 条件分岐
evens = [x for x in [1, 2, 3, 4] if x % 2 == 0]

従来の方法
evens = []
for x in [1, 2, 3, 4]:
    if x % 2 == 0:
        evens.append(x)


④繰り返しが2回 + 条件分岐
even_combinations = [(x, y) for x in [1, 2, 3] for y in [4, 5, 6] if x % 2 == 0 and y % 2 == 0]

従来の方法:
even_combinations = []
for x in [1, 2, 3]:
    for y in [4, 5, 6]:
        if x % 2 == 0 and y % 2 == 0:
            even_combinations.append((x, y))


辞書内包表記

①繰り返しが1回
squares_dict = {x: x**2 for x in [1, 2, 3, 4]}

従来の方法
squares_dict = {}
for x in [1, 2, 3, 4]:
    squares_dict[x] = x**2


②繰り返しが2回
dictionary = {k: v for k in ['a', 'b'] for v in [1, 2]}

従来の方法:
dictionary = {}
for k in ['a', 'b']:
    for v in [1, 2]:
        dictionary[k] = v


③繰り返しが1回 + 条件分岐
even_squares_dict = {x: x**2 for x in [1, 2, 3, 4] if x % 2 == 0}

従来の方法:
even_squares_dict = {}
for x in [1, 2, 3, 4]:
    if x % 2 == 0:
        even_squares_dict[x] = x**2


④繰り返しが2回 + 条件分岐
filtered_dict = {k: v for k in ['a', 'b', 'c'] for v in [1, 2, 3] if v % 2 == 0}

従来の方法:
filtered_dict = {}
for k in ['a', 'b', 'c']:
    for v in [1, 2, 3]:
        if v % 2 == 0:
            filtered_dict[k] = v

 

集合内包表記

①繰り返しが1回
squares_set = {x**2 for x in [1, 2, 3, 4]}

従来の方法:
squares_set = set()
for x in [1, 2, 3, 4]:
    squares_set.add(x**2)


②繰り返しが2回
combinations_set = {(x, y) for x in [1, 2] for y in [3, 4]}

従来の方法:
combinations_set = set()
for x in [1, 2]:
    for y in [3, 4]:
        combinations_set.add((x, y))


③繰り返しが1回 + 条件分岐
even_squares_set = {x**2 for x in [1, 2, 3, 4] if x % 2 == 0}
 

従来の方法:
even_squares_set = set()
for x in [1, 2, 3, 4]:
    if x % 2 == 0:
        even_squares_set.add(x**2)


④繰り返しが2回 + 条件分岐
even_combinations_set = {(x, y) for x in [1, 2, 3] for y in [4, 5, 6] if x % 2 == 0 and y % 2 == 0}

従来の方法:
even_combinations_set = set()
for x in [1, 2, 3]:
    for y in [4, 5, 6]:
        if x % 2 == 0 and y % 2 == 0:
            even_combinations_set.add((x, y))