Python高级用法-推导式
2018/08/07 18:37 分类: 技术交流 浏览:26
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. print(new_prices)
推导式写法
1. prices = [100, 200, 300, 400, 500]
2. new_prices = [int(price * 1.1) for price in prices]
3. print(new_prices)
2. 推导式详解
在Python中存在两种常用的数据结构,分别对应的两种推导式:
- 列表推导式
- 字典推导式
- 列表推导式
语法:
1. [expr for value in collection ifcondition]
collection: 原始列表.
value: 列表中的原始
ifcondition: 过滤value的条件,满足条件再传入expr. 可选表达式
expr: 对满足条件的value进一步处理后生成新的元素放在新的列表中.
需求: 获取0-100的奇数.
常规写法:
1. list = range(0, 101)
2. new_list = []
3. for value in list:
4. if value % 2 == 0:
5. new_list.append(value)
6. print(new_list)
推导式写法
1. list = range(0, 101)
2. new_list = [value for value in list if not value % 2]
3. print(new_list)
- 字典推导式
语法:
1. { key_expr: value_expr for value in collection if condition }
collection: 原始字典或者列表.
value: 列表中的原始
ifcondition: 过滤value的条件,满足条件再传入expr. 可选表达式
expr: 对满足条件的value进一步处理后生成新的元素放在新的列表中.
需求:将第一个列表中的元素作为键,第二个列表中的元素作为值生成新的字典.
常规写法:
1. questions = ['name', 'quest', 'favorite color']
2. answers = ['lancelot', 'the holy grail', 'blue']
3.
4. new_dict = {}
5. for q, a in zip(questions, answers):
6. new_dict[q] = a
7. print(new_dict)
zip()函数可以成对读取元素
推导式写法
1. questions = ['name', 'quest', 'favorite color']
2. answers = ['lancelot', 'the holy grail', 'blue']
3.
4. new_dict = {q: a for q, a in zip(questions, answers) if not q == "name"}
5. print(new_dict)
赞 0