Python在方括号中使用for循环,类似[0foriinrange(10)],叫列表解析...
作者博文地址: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中大于等于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 要求:列出'/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 使用列表解析生成 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倍。因此推荐使用列表解析。
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
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:
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:
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 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:
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: