# Python代码分享_Python推导式快速体验

XAMPP案例 660浏览
#今日Python分享#

## 快速体验

• while循环实现
``````# 1. 准备一个空列表
list1 = []

# 2. 书写循环，依次追加数字到空列表list1中
i = 0
while i < 10:
list1.append(i)
i += 1

print(list1)``````
• for循环实现
``````list1 = []
for i in range(10):
list1.append(i)

print(list1)``````
• 列表推导式实现
``````list1 = [i for i in range(10)]
print(list1)``````

## 带if的列表推导式

• 方法一：range()步长实现
``````list1 = [i for i in range(0, 10, 2)]
print(list1)``````
• 方法二：if实现
``````list1 = [i for i in range(10) if i % 2 == 0]
print(list1)``````

## 多个for循环实现列表推导式

``[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]``
• 代码如下：
``````list1 = [(i, j) for i in range(1, 3) for j in range(3)]
print(list1)``````
#01#

``````list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']``````

# 快速体验

1. 创建一个字典：字典key是1-5数字，value是这个数字的2次方。
``````dict1 = {i: i**2 for i in range(1, 5)}
print(dict1)  # {1: 1, 2: 4, 3: 9, 4: 16}``````
1. 将两个列表合并为一个字典
``````list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']

dict1 = {list1[i]: list2[i] for i in range(len(list1))}
print(dict1)``````
1. 提取字典中目标数据
``````counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}

# 需求：提取上述电脑数量大于等于200的字典数据
count1 = {key: value for key, value in counts.items() if value >= 200}
print(count1)  # {'MBP': 268, 'DELL': 201}``````
#02#

``list1 = [1, 1, 2]``

``````list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1)  # {1, 4}``````

#03#

• 推导式的作用：简化代码
• 推导式写法
``````# 列表推导式
[xx for xx in range()]

# 字典推导式
{xx1: xx2 for ... in ...}

# 集合推导式
{xx for xx in ...}``````