标签:append strip blog 整理 python range 程序 list style
列表表达式
程序一:
常规写法:
egg_list=[] for i in range(100): egg_list.append(‘egg%s‘ %i) print(egg_list)
列表表达式写法:
l=[‘egg%s‘ %i for i in range(100) if i > 0] print(l)
程序二:
常规写法:
l=[1,2,3,4] s=‘hello‘ l1=[] for num in l: for s1 in s: t=(num,s1) l1.append(t) print(l1)
列表表达式写法:
l1=[(num,s1) for num in l if num > 2 for s1 in s] print(l1)
程序三:
常规写法:
import os g=os.walk(‘F:\\xuyaping‘) file_path_list=[] for i in g: # print(i) for j in i[-1]: file_path_list.append(‘%s\\%s‘ %(i[0],j)) print(file_path_list)
列表表达式写法:
g=os.walk(‘F:\\xuyaping‘) l1=[‘%s\\%s‘ %(i[0],j) for i in g for j in i[-1]] print(l1)
生成器表达式
相比列表表达式,只不过将[]换成了(),更加省内存。
程序一:
列表表达式写法:
l=[‘egg%s‘ %i for i in range(10000)] print(l)
生成器表达式写法:
g=l=(‘egg%s‘ %i for i in range(10000)) print(g) print(next(g)) print(next(g)) for i in g: print(i)
程序二:
常规写法:
f=open(‘a.txt‘) l=[] for line in f: line=line.strip() l.append(line) print(l)
列表表达式写法:
f=open(‘a.txt‘) f.seek(0) l1=[line.strip() for line in f] print(l1)
生成器表达式写法:
f.seek(0) g=(line.strip() for line in f) print(g) print(next(g))
以下待整理......
f=open(‘a.txt‘) g=(line.strip() for line in f) l=list(g) print(l) nums_g=(i for i in range(3)) # print(sum([1,2,3,4])) print(sum(nums_g))
标签:append strip blog 整理 python range 程序 list style
原文地址:http://www.cnblogs.com/xuyaping/p/6701973.html