作者博文地址:/liu-shuai/
列表解析
根据已有列表,高效创建新列表的方式。
列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,因此用在[]中。
语法:
[expression for iter_val in iterable]
[expression for iter_val in iterable if cond_expr]
实例展示:
1 要求:列出1~10所有数字的平方
2 ####################################################
3 1、普通方法: 4 >>> L = [] 5 >>> for i in range(1,11): 6 ... (i**2) 7 ... 8 >>> print L 9 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 10 #################################################### 11 2、列表解析 12 >>>L = [ i**2 for i in range(1,11)] 13 >>>print L 14 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1 要求:列出1~10中大于等于4的数字的平方
2 ####################################################
3 1、普通方法: 4 >>> L = [] 5 >>> for i in range(1,11): 6 ... if i >= 4: 7 ... (i**2) 8 ... 9 >>> print L 10 [16, 25, 36, 49, 64, 81, 100] 11 #################################################### 12 2、列表解析 13 >>>L = [ i**2 for i in range(1,11) if i >= 4 ] 14 >>>print L 15 [16, 25, 36, 49, 64, 81, 100]
1 要求:列出1~10所有数字的平方除以2的值
2 ####################################################
3 1、普通方法 4 >>> L = [] 5 >>> for i in range(1,11): 6 ... (i**2/2) 7 ... 8 >>> print L 9 [0, 2, 4, 8, 12, 18, 24, 32, 40, 50] 10 #################################################### 11 2、列表解析 12 >>> L = [i**2/2 for i in range(1,11) ] 13 >>> print L 14 [0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
1 要求:列出"/var/log"中所有已'.log'结尾的文件 2 ################################################## 3 1、普通方法 4 >>>import os 5 >>>file = [] 6 >>> for file in ('/var/log'): 7 ... if ('.log'): 8 ... (file) 9 ... 10 >>> print file 11 ['', 'Xorg.', '', 'Xorg.', '', '', '', '', '', 'wpa_supplicant.log', '', '', ''] 12 ################################################## 13 2.列表解析 14 >>> import os 15 >>> file = [ file for file in ('/var/log') if ('.log') ] 16 >>> print file 17 ['', 'Xorg.', '', 'Xorg.', '', '', '', '', '', 'wpa_supplicant.log', '', '', '']
1 要求:实现两个列表中的元素逐一配对。
2 1、普通方法:
3 >>> L1 = ['x','y','z'] 4 >>> L2 = [1,2,3] 5 >>> L3 = [] 6 >>> for a in L1: 7 ... for b in L2: 8 ... ((a,b)) 9 ... 10 >>> print L3 11 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)] 12 #################################################### 13 2、列表解析: 14 >>> L1 = ['x','y','z'] 15 >>> L2 = [1,2,3] 16 L3 = [ (a,b) for a in L1 for b in L2 ] 17 >>> print L3 18 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
1 使用列表解析生成 9*9 乘法表
2
3 print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))
说明:
以上实例,使用列表解析比使用普通方法的速度几乎可以快1倍。因此推荐使用列表解析。
/3/tutorial/#list-comprehensions
5.1.3. List Comprehensions
List comprehensions provide a concise way to create applications are to make new lists where each element is the result ofsome operations applied to each member of another sequence or iterable, or tocreate a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Note that this creates (or overwrites) a variable named x
that still existsafter the loop completes. We can calculate the list of squares without anyside effects using:
squares = list(map(lambda x: x**2, range(10)))
or, equivalently:
squares = [x**2 for x in range(10)]
which is more concise and readable.
A list comprehension consists of brackets containing an expression followedby a for clause, then zero or more for or ifclauses. The result will be a new list resulting from evaluating the expressionin the context of the for and if clauses which follow example, this listcomp combines the elements of two lists if they are notequal:
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
and it’s equivalent to:
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Note how the order of the for and if statements is thesame in both these snippets.
If the expression is a tuple (. the (x, y)
in the previous example),it must be parenthesized.
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in <module>
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List comprehensions can contain complex expressions and nested functions:
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']