列表推导式#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)
x = [i*i for i in y]
print(x)
#100以内数的一半 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)

列表推导式转换生成器表达式
l = ['鸡蛋%s'%i for i in range(10)]
print(l)
laomuji = ('鸡蛋%s'%i for i in range(10))
for egg in laomuji:
    print(egg)

30以内能被三整除的数

#for循环
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]

平方补充square

def square(x):
    return x*x


[square(i) for i in range(30) if i%3 == 0]

找出列表中含有两个或两个以上“e”的元素

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)

字典表达式

#key,value互换
mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]:k for k in mcase} print(mcase_frequency)
#key合并同名为小写,value相加
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))  #[]
def add(n,i):
    return n+i

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

g=tes()
for n in [1,5,10]:
    g=(add(n,i) for i in g)
# n=1
# g=(add(n,i) for i in tes())
# n = 5
# g=(add(n,i) for i in (add(n,i) for i in tes()))
# n = 10
# g=(add(n,i) for i in (add(n,i) for i in (add(n,i) for i in tes())))
print(list(g))  #[30, 31, 32, 33]

 

posted on 2017-11-08 20:41  Py行僧  阅读(154)  评论(0编辑  收藏  举报