## 列表解析表达式

[expr for iter_var in iterable]
[expr for iter_var in iterable if cond_expr]

>>> L= [(x+1,y+1) for x in range(3) for y in range(5)]
>>> L
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]
>>> N=[x+10for x in range(10) if x>5]
>>> N
[16, 17, 18, 19]
newlist=[x+5for x in olderlist if x>10]

>>> num = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> num
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 10, 15, 20, 25, 30, 35, 40, 45, 12, 18, 24, 30, 36, 42, 48, 14, 21, 28, 35, 42, 49]

>>> words ='The quick brown fox jumps over the lazy dog'.split()
>>> words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]
>>>for i in stuff:
print i

['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

>>> stuff = map(lambda w: [w.upper(), w.lower(), len(w)], words)
>>>for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

## 列表生成器表达式

(expr for iter_var in iterable)
(expr for iter_var in iterable if cond_expr)

>>> L= (i +1for i in range(10) if i %2)
>>> L
<generator object <genexpr> at 0xb749a52c>
>>> L1=[]
>>>for i in L:
... L1.append(i)
...
>>> L1
[2, 4, 6, 8, 10]

A generator object in python is something like a lazy list. The
elements are only evaluated as soon as you iterate over them.

## 一些说明

1.当需求只是执行一个循环操作的时候，尽量使用循环而不是列表解析，这样更符合python提倡的直观性

for item in sequence:
process(item)

2.当有内建的操作或者类型能够以更直接的方式实现的，不要使用列表解析

L1=[x for x in L]

3.当序列过长， 而每次只需要获取一个元素时，使用生成器表达式
4.列表解析的性能要比map要好，实现相同功能的for循环效率最差（和列表解析相比差两倍）
5.列表解析可以转换为 for循环或者使用map（其中可能会用到filter、lambda函数）表达式，但是列表解析更为简单明了，后者会带来更复杂和深层的嵌套

#### [转]Python里有趣的列表解析和生成器表达式

2014-07-15 20:14:20

#### Python列表解析配合if else

2017-05-30 11:36:54

#### Python 列表解析和生成器表达式

2013-12-23 15:31:43

#### 列表解析和生成式表达式

2014-04-03 11:14:42

#### 列表解析及生成器表达式的效率问题

2016-04-18 05:48:53

#### 深入理解python的生成器表达式和列表解析

2017-07-29 08:07:12

#### Python列表解析（列表推导式）

2017-02-13 17:16:58

#### Python中的列表解析和生成表达式

2013-05-23 20:27:03

#### Python（8）： Lambda，列表解析器，生成器表达式，range函数

2017-02-28 15:43:24

#### python-map/列表解析

2016-08-18 15:14:00

## 不良信息举报

python中的列表解析和列表生成表达式