Python在方括號中使用for迴圈,類似[0 for i in range(10)],叫 列表解析List Comprehensions
作者博文地址:https://www.cnblogs.com/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 ... L.append(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 ... L.append(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 ... L.append(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 os.listdir('/var/log'):
7 ... if file.endswith('.log'):
8 ... file.append(file)
9 ...
10 >>> print file
11 ['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']
12 ##################################################
13 2.列表解析
14 >>> import os
15 >>> file = [ file for file in os.listdir('/var/log') if file.endswith('.log') ]
16 >>> print file
17 ['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.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 ... L3.append((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倍。因此推薦使用列表解析。
5.1.3. List Comprehensions
List comprehensions provide a concise way to create lists.Common 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 if
clauses. The result will be a new list resulting from evaluating the expressionin the context of the for
and if
clauses which follow it.For 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 (e.g. 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']