一、dict推导式
list1 = ['name', 'age', 'gender']
list2 = ['zmz', '20', 'boy']
dict1 = {i: i ** 2 for i in range(1, 5)}
print(dict1)
dict2 = {list1[i]: list2[i]for i in range(len(list1))}
print(dict2)
dict3 = {'Mac': 10000, 'Dell': 6599, 'HP': 6999, 'Lenovo': 5799, 'Acer': 4599}
print(dict3.items())
counts = {key: value for key, value in dict3.items() if value > 6000}
print(counts)
二、list推导式
"""
推导式(生成式) -- 是用来化简代码
推导式包含:
1.列表推导式
2.字典推导式
3.集合推导式
"""
list1 = []
i = 0
while i < 10:
list1.append(i)
i += 1
print(list1)
list2 = []
for i in range(10, 20, 1):
list2.append(i)
print(list2)
list3 = [i for i in range(-9, 2, 1)]
print(list3)
print(sum([2 ** i for i in range(100)]))
三、set推导式
list1 = [2, 3, 4, 2, 5, 3]
set1 = {i ** 2 for i in list1}
print(set1)
t1 = (10, 20, 30, 40, 50)
print(t1)
t2 = (i * 2 for i in t1)
print(t2)
四、含if推导式
"""
创建0 - 10 的偶数列表
"""
list1 = [i for i in range(0, 11, 2)]
print(list1)
list2 = []
for i in range(11):
if i % 2 == 0:
list2.append(i)
print(list2)
list3 = [i for i in range(11) if i % 2 == 0]
print(list3)
五、含for推导式
list = []
for i in range(1, 3):
for j in range(3):
list.append((i, j))
print(list)
print("==================")
list1 = [(i, j) for i in range(5) for j in range(5)]
count = 0
for i in list1:
count += 1
print(i, end='')
if count % 5 == 0:
print()
|