源码干货

Python高级用法-推导式

2018-08-08  本文已影响8人  源码时代官方

Python高级用法-推导式

1. 什么是推导式

Python推导式是从一个数据集合构建另外一个新的数据结构的语法结构.

1.1. 推导式入门体验

需求: 将列表中的每个价格上涨10%.

常规写法:

prices = [100, 200, 300, 400, 500]

new_prices = [] #新的列表准备放新的价格

for price in prices: #循环出每个价格

new_prices.append(int(price*1.1)) #生成新价格并且存放在新的列表中

print(new_prices)

推导式写法

prices = [100, 200, 300, 400, 500]

new_prices = [int(price * 1.1) for price in prices]

print(new_prices)

2. 推导式详解

在Python中存在两种常用的数据结构,分别对应的两种推导式:

a. 列表推导式

b. 字典推导式

2.2. 列表推导式

语法:

[expr for value in collection ifcondition]

collection: 原始列表.

value: 列表中的原始

ifcondition: 过滤value的条件,满足条件再传入expr. 可选表达式

expr: 对满足条件的value进一步处理后生成新的元素放在新的列表中.

需求: 获取0-100的奇数.

常规写法:

list = range(0, 101)

new_list = []

for value in list:

if value % 2 == 0:

new_list.append(value)

print(new_list)

推导式写法:

list = range(0, 101)

new_list = [value for value in list if not value % 2]

print(new_list)

2.3. 字典推导式

语法:

{ key_expr: value_expr for value in collection if condition }

collection: 原始字典或者列表.

value: 列表中的原始

ifcondition: 过滤value的条件,满足条件再传入expr. 可选表达式

expr: 对满足条件的value进一步处理后生成新的元素放在新的列表中.

需求:将第一个列表中的元素作为键,第二个列表中的元素作为值生成新的字典.

常规写法:

​questions = ['name', 'quest', 'favorite color']

answers = ['lancelot', 'the holy grail', 'blue']

new_dict = {}

for q, a in zip(questions, answers):

new_dict[q] = a

print(new_dict)

zip()函数可以成对读取元素

推导式写法

questions = ['name', 'quest', 'favorite color']

answers = ['lancelot', 'the holy grail', 'blue']

new_dict = {q: a for q, a in zip(questions, answers) if not q == "name"}

print(new_dict)

上一篇下一篇

猜你喜欢

热点阅读