列表推导式、字典推导式、集合推导式

列表生成式(列表推导式)

# 1. 提取出1-20之间的奇数
odd_list = []
for i in range(21):
    if i%2 == 1:
        odd_list.append(i)

print(odd_list)

odd_list = [i for i in range(21) if i%2 == 1]
print(odd_list)
image.png
# 2.逻辑复杂的情况
def hadle_item(item):
    return item * item
odd_list = [hadle_item(i) for i in range(21) if i%2 == 1]
print(odd_list)
image.png

字典推导式

my_dict = {"bobby1":22, "bobby2":23, "imooc.com":5}
reversed_dict = {value:key for key,value in my_dict.items()}
print(reversed_dict)
image.png

集合推导式

my_dict = {"bobby1":22, "bobby2":23, "imooc.com":5}
my_set = {key for key, value in my_dict.items()}
print(type(my_set))
print(my_set)
image.png

你可能感兴趣的:(列表推导式、字典推导式、集合推导式)