1 列表推导式定义
列表推导式能非常简洁的构造一个新列表:只用一条简洁的表达式即可对得到的元素进行转换变形
2 列表推导式语法
基本格式如下:
[expr for value in collection ifcondition]
过滤条件可有可无,取决于实际应用,只留下表达式
列表推导式例子:
1 2 | l=["egg%s"%i for i in range(10)] print(l) |
---|
类似于这段for代码:
1 2 3 4 | egg_list=[] for i in range(10): egg_list.append("egg%s"%i) print(egg_list) |
---|
列表推导式还可以加更多的if判断for循环
1 2 3 4 | l=['egg%s' %i for i in range(1,101)] l=['egg%s' %i for i in range(1,101) if i >50 ] l=['egg%s' %i for i in range(1,101) if i >50 if i<60] print(l) |
---|
3 列表推导式优点
方便,改变了编程习惯,属于声明式编程
举例:
1 2 3 4 | l=[1,2,3,4] s="hello" l1=[(num,i) for num in l for i in s] print(l1) |
---|
输出结果为:
1 | [(1, 'h'), (1, 'e'), (1, 'l'), (1, 'l'), (1, 'o'), (2, 'h'), (2, 'e'), (2, 'l'), (2, 'l'), <br>(2, 'o'), (3, 'h'), (3, 'e'), (3, 'l'), (3, 'l'), (3, 'o'), (4, 'h'), (4, 'e'), (4, 'l'), <br>(4, 'l'), (4, 'o')] |
---|
这个列表推导式相当于:
1 2 3 4 5 6 7 8 | l=[1,2,3,4] s="hello" l1=[] for num in l: for i in s: t=(num,i) l1.append(t) print(l1) |
---|
4 列表表达式例子
1 2 3 4 5 6 7 8 9 10 11 | import os g=os.walk("C:\python_fullstack_wen\day24\wen") file_path_list=[] for i in g: for j in i[-1]: file_path_list.append("%s\\%s"%(i[0],j)) print(file_path_list) g=os.walk("C:\python_fullstack_wen\day24\wen") file_path_list=["%s\\%s"%(i[0],j) for i in g for j in i[-1]] print(file_path_list) |
---|
输出结果:
1 2 | ['C:\\python_fullstack_wen\\day24\\wen\\yan1.txt', 'C:\\python_fullstack_wen\\day24\\wen\\wen1<br>\\yan1.txt', 'C:\\python_fullstack_wen\\day24\\wen\\wen1\\jie1\\yan1.txt', <br>'C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1\\yan1.txt', <br>'C:\\python_fullstack_wen\\day24\\wen\\wen2\\yan2.txt'] ['C:\\python_fullstack_wen\\day24\\wen\\yan1.txt', 'C:\\python_fullstack_wen\\day24\\wen\\wen1\\yan1.txt', 'C: |
---|