通过我们直接给定值、或者通过其他序列转换之外,我们还可以通过推导式进行创建一个列表、字典或集合。
⽤⼀个表达式创建⼀个有规律的容器。
list = [表达式]
普通实现:
list1 = []
for i in range(10):
list1.append(i)
print(list1)
list1 = [i for i in range(10)]
print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [i for i in range(10) if i % 2 == 0]
print(list2) # [0, 2, 4, 6, 8]
list3 = [(i, j) for i in range(1, 3) for j in range(2)]
print(list3) # [(1, 0), (1, 1), (2, 0), (2, 1)]
dict1 = {i: i**2 for i in range(1, 5) if i % 2 == 0}
print(dict1) # {2: 4, 4: 16}
dict1 = {i: i**2 for i in range(1, 5)}
print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}
list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
dict1 = {list1[i]: list2[i] for i in range(len(list1))}
print(dict1) # {'name': 'Tom', 'age': 20, 'gender': 'man'}
带if的推导式
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199}
# 需求:提取上述电脑数量⼤于等于200的字典数据
count1 = {key: value for key, value in counts.items() if value > 200}
print(count1) # {'MBP': 268, 'DELL': 201}
和列表用法基本一致
list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1) # {1, 4}