1.
什么是推导式
Python
推导式是从一个数据集合构建另外一个新的数据结构的语法结构
.
推导式入门体验
需求
:
将列表中的每个价格上涨
10%.
常规写法
:
1. prices = [100, 200, 300, 400, 500]
2. new_prices = [] #
新的列表准备放新的价格
3.
for
price
in
prices: #
循环出每个价格
4. new_prices.append(int(price*1.1)) #
生成新价格并且存放在新的列表中
5.
(new_prices)
推导式写法
1. prices = [100, 200, 300, 400, 500]
2. new_prices = [int(price * 1.1)
for
price
in
prices]
3.
(new_prices)
2.
推导式详解
在
Python
中存在两种常用的数据结构
,
分别对应的两种推导式
:
列表推导式
字典推导式
列表推导式
语法
:
1. [expr
for
value
in
collection ifcondition]
collection:
原始列表
.