列表推导式:

通过列表y得到列表x:

y = [1,2,3,4,5,6,7,8]
x = [1,4,9,16,25,36,49,64]

一般我们会这么做:

x = []
for i in y:
    x.append(i*i)
print(x)

 列表推导式:

y = [1,2,3,4,5,6,7,8]

x = [i*i for i in y]
print(x)

再看一个例子:

range(100)
x2 = [i/2 for i in range(100)]
print(x2)

生成器表达式:

x = [i*i for i in y]
print(x)
g = (i*i for i in y)
print(g)
print(list(g))
for i in g:
    print(i)

老母鸡的例子:

#老男孩由于峰哥的强势加盟很快走上了上市之路,alex思来想去决定下几个鸡蛋来报答峰哥

egg_list=['鸡蛋%s' %i for i in range(10)] #列表解析

#峰哥瞅着alex下的一筐鸡蛋,捂住了鼻子,说了句:哥,你还是给我只母鸡吧,我自己回家下

laomuji=('鸡蛋%s' %i for i in range(10))#生成器表达式
print(laomuji)
print(next(laomuji)) #next本质就是调用__next__
print(laomuji.__next__())
print(next(laomuji))

l = ['鸡蛋%s'%i for i in range(10)]
# print(l)
laomuji = ('鸡蛋%s'%i for i in range(10))
for egg in laomuji:
    print(egg)

各种推导式:

new_l = []
for i in range(30):
    if i%3 == 0:
        new_l.append(i)
print(new_l)

 

# print(list(range(0,30,3)))
# print([i for i in range(30) if i%3 == 0])
# [i*i for i in range(30) if i%3 == 0]
# def square(x):
#     return x*x
# [square(i) for i in range(30) if i%3 == 0]

 

# names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
#          ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
# ret = (name for name_lst in names for name in name_lst if name.count('e') >= 2)
# print(ret)

# 不利于代码可读,但是代码简洁

 

# mcase = {'a': 10, 'b': 34} # mcase_frequency = {mcase[k]:k for k in mcase} # print(mcase_frequency)

# mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} # mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase} # print(mcase_frequency)

squared = {x**2 for x in [1, -1, 2]}   #{1,4} print(squared) # Output: set([1, 4])     

面试题:

def demo():
    for i in range(4):
        yield i

g=demo()   # 生成器

g1=(i for i in g) #生成器
g2=(i for i in g1) #g2 生成器

# print(list(g1))   #[0,1,2,3]
print(list(g2))    
    

总结:

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

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

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