列表解析式
- [返回值 for 元素 in 可迭代对象 if 条件]
- 使用[ ],内部是for循环,,if条件语句可选
- 返回一个新的列表
- 编译器会优化,不会因为简写而影响效率,反而因优化提高了效率
- 减少程序员工作量,减少出错
- 简化了代码,但可读性差一点
### 求10以内的偶数集
# 非列表解析式写法
even =[]
for x in rang(10):
if x % 2 == 0:
even.append(x)
# ------------------------------ #
# 列表解析式写法
even = [x for x in range(10) if x%2 == 0] # [0, 2, 4, 6, 8]
- [expr for item in iterable if cond1 if cond2] # 不允许出现else
- 等价于
ret = []
for iterm in iterable:
if cond1:
if cond2:
ret.append(expr)
### 20以内,既能被2整除又能被3整除的数
>>> res = [i for i in range(20) if i%2 == 0 and i%3 == 0]
[0, 6, 12, 18]
>>> res = [i for i in range(20) if i%2 == 0 if i%3 == 0]
[0, 6, 12, 18]
- [expr for i in iterable1 for j in iterable2 ]
- 等价于
ret = []
for i in iterable1:
for j in iterable2:
ret.append(expr)
>>> res = [(x,y) for x in 'abc' for y in range(3)]
[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)]
>>> res = [(x,y) for x in range(7) if x >4 for y in range(20,25) if y>23]
[(5, 24), (6, 24)]
>>> res = [(x,y) for x in range(7) for y in range(20,25)if x>4 if y>23]
[(5, 24), (6, 24)]
>>> res = [(x,y) for x in range(7) for y in range(20,25)if x>4 and y>23]
[(5, 24), (6, 24)]
集合解析式
- {返回值for 元素 in可迭代对象 if 条件}
- 列表解析式的[]换成{}即可
- 立即返回一个集合
>>> {(x, x+1) for x in range(10)}
{(0, 1), (1, 2), (7, 8), (6, 7), (4, 5), (5, 6), (8, 9), (9, 10), (2, 3), (3, 4)}
## - 注: {[x] for x in range(10)},会报TypeError错误,因为[x]是list,集合内的元素需要可hash,而list是不可hash
字典解析式
- {返回值for 元素 in可迭代对象 if 条件}
- 列表解析式的[]换成{}即可
- 使用key.value形式
- key值需要可hash
- 立即返回一个字典
>>> res = {x:(x,x+1) for x in range(5)}
{0: (0, 1), 1: (1, 2), 2: (2, 3), 3: (3, 4), 4: (4, 5)}
>>> res = {x:[x,x+1] for x in range(5)}
{0: [0, 1], 1: [1, 2], 2: [2, 3], 3: [3, 4], 4: [4, 5]}
>>> res = {(x,):[x,x+1] for x in range(5)}
{(0,): [0, 1], (1,): [1, 2], (2,): [2, 3], (3,): [3, 4], (4,): [4, 5]}