Python在方括号中使用for循环,类似[0 for i in range(10)],叫 列表解析List Comprehensions
2018-04-04 14:22
961 查看
https://www.cnblogs.com/liu-shuai/p/6098227.html
Python 列表解析
作者博文地址: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 ######### 4000 ########################################### 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倍。因此推荐使用列表解析。
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 oce97
f 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
xthat 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
forclause, then zero or more
foror
ifclauses. The result will be a new list resulting from evaluating the expressionin the context of the
forand
ifclauses 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
forand
ifstatements 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']
相关文章推荐
- Python学习笔记十二:列表(4)--len 、in、For的使用
- 零基础学python-12.5 修改列表的误区以及使用for和range修改列表
- python jpype 调用Hanlp,使用列表解析.toString.encode("utf-8") 会出现乱码,需用使用for 循环
- 零基础学python-12.5 修改列表的误区以及使用for和range修改列表
- Python:列表中len、in、For的使用案例
- Python(5)使用for...in循环和列表推导式打印一个99乘法表
- 零基础学python-12.5 修改列表的误区以及使用for和range修改列表
- Effective JavaScript Item 49 对于数组遍历,优先使用for循环,而不是for..in循环
- 零基础学python-13.4 文件上使用列表解析与列表解析扩展
- fs = [(lambda n, i=i : i + n) for i in range(10)]
- Learning Python:1. 生成器函数、列表解析与map,for循环的效率对比
- python中的for i in range
- python列表解析不写for循环do something
- [Effective JavaScript 笔记]第49条:数组迭代要优先使用for循环而不是for...in循环
- python for in range
- Python比较for循环、列表解析、迭代器、map之间运算时间关系
- 零基础学python-13.4 文件上使用列表解析与列表解析扩展
- 使用python的列表解析以及函数式计算来简化代码
- 零基础学python-12.4 while、for与range联合使用
- 使用python的列表解析以及函数式计算来简化代码