[ 運算式 for 變數(item) in 可迭代的物件(iterable) if 條件]
x = [1, 2, 3, 4]
x_list = [item * 2 for item in x]
print(x_list)
# [2, 4, 6, 8]
x_list = [item * 2 for item in x if item % 2 == 0]
print(x_list)
# [4, 8]
x_list = [item if item > 2 else 0 for item in x ]
print(x_list)
# [0, 0, 3, 4]
{ key 運算式:value 運算式 for 變數(item) in 可迭代的物件(iterable) if 條件}
x_dict = {item:item * 2 for item in x}
print(x_dict)
# {1: 2, 2: 4, 3: 6, 4: 8}
x_dict = {item:item * 2 for item in x if item > 2}
print(x_dict)
# {3: 6, 4: 8}
x_dict = {f"{item}":item if item > 2 else 0 for item in x }
print(x_dict)
# {'1': 0, '2': 0, '3': 3, '4': 4}
[]
變更為 ()
,並不是 truple,而是一個 generator(產生器)
x = [1, 2, 3, 4]
x_list = [item * 2 for item in x]
print(x_list)
# [2, 4, 6, 8]
x_gen = (item * 2 for item in x)
print(x_gen)
# generator object
來看看 type hint 吧!