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

结论:

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

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

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

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

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

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

 ♥♥♥。◕‿◕。♥♥♥

一、列表生成式

1 #三元表达式
2 name='alex'
3 name='egon'
4 
5 res='SB' if name == 'alex' else 'shuai'
6 print(res)

 

1 #例子1
2 egg_list=[]
3 
4 for i in range(100):
5     egg_list.append('egg%s' %i)
6 print(egg_list)
7 
8 l=['egg%s' %i for i in range(100) if i > 50]
9 print(l)

 

 1 #例子2
 2 l=[1,2,3,4]
 3 s='hello'
 4 
 5 l1=[(num,s1) for num in l if num > 2 for s1 in s]
 6 print(l1)
 7 
 8 l1=[]
 9 for num in l:
10     for s1 in s:
11         t=(num,s1)
12         l1.append(t)
13 print(l1)

 

 1 #例子3
 2 import os
 3 g=os.walk('C:\\egon')
 4 file_path_list=[]
 5 for i in g:
 6     # print(i)
 7     for j in i[-1]:
 8         file_path_list.append('%s\\%s' %(i[0],j))
 9 
10 print(file_path_list)
11 
12 g=os.walk('C:\\egon')
13 l1=['%s\\%s' %(i[0],j) for i in g for j in i[-1]]
14 print(l1)

 

二、生成器表达式

 1 #例子1
 2 l=['egg%s' %i for i in range(100)]
 3 print(l)
 4 
 5 g=l=('egg%s' %i for i in range(10000))
 6 print(g)
 7 print(next(g))
 8 print(next(g))
 9 for i in g:
10     print(i)

 

 1 #例子2
 2 f=open('a.txt')
 3 l=[]
 4 for line in f:
 5     line=line.strip()
 6     l.append(line)
 7 
 8 print(l)
 9 f.seek(0)
10 l1=[line.strip() for line in f]
11 print(l1)
12 
13 f.seek(0)
14 g=(line.strip() for line in f)
15 print(g)
16 print(next(g))

 

 1 #例子3
 2 f=open('a.txt')
 3 g=(line.strip() for line in f)
 4 
 5 l=list(g)
 6 print(l)
 7 
 8 nums_g=(i for i in range(3))
 9 
10 # print(sum([1,2,3,4]))
11 print(sum(nums_g))

 

 1 #例子4
 2 money_l=[]
 3 with open('b.txt') as f:
 4     for line in f:
 5         goods=line.split()
 6         res=float(goods[-1])*float(goods[-2])
 7         money_l.append(res)
 8 print(money_l)
 9 
10 f=open('b.txt')
11 g=(float(line.split()[-1])*float(line.split()[-2]) for line in f)
12 
13 print(sum(g))
14 
15 with open('b.txt') as f:
16     print(sum((float(line.split()[-1])*float(line.split()[-2]) for line in f)))

 

 1 #例子5
 2 res=[]
 3 with open('b.txt') as f:
 4     for line in f:
 5         # print(line)
 6         l=line.split()
 7         # print(l)
 8         d={}
 9         d['name']=l[0]
10         d['price']=l[1]
11         d['count']=l[2]
12         res.append(d)
13 print(res)

  

posted @ 2017-04-12 17:12  ForeverPine  阅读(352)  评论(0编辑  收藏  举报
TOP