python基础----列表生成式、生成器表达式

时间:2024-12-06 14:33:56

结论:

1.把列表解析的[]换成()得到的就是生成器表达式

2.列表解析与生成器表达式都是一种便利的编程方式,只不过生成器表达式更节省内存

3.Python不但使用迭代器协议,让for循环变得更加通用。大部分内置函数,也是使用迭代器协议访问对象的。例如, sum函数是Python的内置函数,该函数使用迭代器协议访问对象,而生成器实现了迭代器协议,所以,我们可以直接这样计算一系列值的和:

sum(x ** 2 for x in xrange(4))

而不用多此一举的先构造一个列表:

sum([x ** 2 for x in xrange(4)]) 

♥♥♥。◕‿◕。♥♥♥

一、列表生成式

 #三元表达式
name='alex'
name='egon' res='SB' if name == 'alex' else 'shuai'
print(res)
 #例子1
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 > 50]
print(l)
 #例子2
l=[1,2,3,4]
s='hello' l1=[(num,s1) for num in l if num > 2 for s1 in s]
print(l1) l1=[]
for num in l:
for s1 in s:
t=(num,s1)
l1.append(t)
print(l1)
 #例子3
import os
g=os.walk('C:\\egon')
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('C:\\egon')
l1=['%s\\%s' %(i[0],j) for i in g for j in i[-1]]
print(l1)

二、生成器表达式

 #例子1
l=['egg%s' %i for i in range(100)]
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)
 #例子2
f=open('a.txt')
l=[]
for line in f:
line=line.strip()
l.append(line) print(l)
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))
 #例子3
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))
 #例子4
money_l=[]
with open('b.txt') as f:
for line in f:
goods=line.split()
res=float(goods[-1])*float(goods[-2])
money_l.append(res)
print(money_l) f=open('b.txt')
g=(float(line.split()[-1])*float(line.split()[-2]) for line in f) print(sum(g)) with open('b.txt') as f:
print(sum((float(line.split()[-1])*float(line.split()[-2]) for line in f)))
 #例子5
res=[]
with open('b.txt') as f:
for line in f:
# print(line)
l=line.split()
# print(l)
d={}
d['name']=l[0]
d['price']=l[1]
d['count']=l[2]
res.append(d)
print(res)