推导式&匿名函数

各种式

列表推导式

1. 求30以内能被3整除的数

print([f'能被三整除的数:{n}' for n in range(1,30) if n %3==0])
View Code

2. 求 30 以内能被 3 整除的数的平方.

print([f'能被三整除的数的平方:{n**n}' for n in range(1,30) if n %3==0])
View Code

3. 找到名字中含有 tt 两个字母的数据

names = [['tom','ttom','jin','jon','jjon','jott'],['jill','bob','bobtt']]

names = [['tom','ttom','jin','jon','jjon','jott'],['jill','bob','bobtt']]
print([i for key in names for i in key if i.count('t') >=2])
print([i for key in names for i in key if 'tt' in i ])
View Code

生成器表达式

和列表推导式基本一样,优点节约内存

g = (f'第{i}个' for i in range(1,10))
print(g) # <generator object <genexpr> at 0x00000267A110F8C8>
for i in g:
    print(i)
View Code

三元表达式

# 三元表达式
i = 1
num = i if 10 < i else 10
print(num)

字典推导式

1. 将字典的 key 和 value 对调

# key 和 value 对调
key1 = {'a':10,'b':20}
key2 = {key1[key]:key for key in key1}
print(key2)

2.  将字典的 key 统一成小写

myk = {'a':2,'b':10,'A':8,'B':20}

new_myk ={key.lower():myk.get(key.lower(),0)+myk.get(key.upper(),0) for key in myk.keys()}
print(new_myk)

 

集合推导式

squared = [ x**2  for x in [1,-1,1,-2,2,3]]  # [1, 1, 1, 4, 4, 9]
squared = { x**2  for x in [1,-1,1,-2,2,3]}  # {1, 4, 9}
print(squared)

匿名函数

    匿名函数: 为了解决某些功能和简单的需求而设计的也是一句话函数.

    匿名函数主要通常和 zip, filter, map, sorted 等函数配合使用

简单练习:

func = lambda n:n**n
print(func(10))

练习题

1. 求字典中 value 值最大的数

dic = {'k1':10,'k2':20,'k3':30,'k4':12}

dic = {'k1':10,'k2':20,'k3':30,'k4':12}
print(max(dic,key=lambda key : dic[key]))
print(dic[max(dic,key=lambda key : dic[key])])
View Code

2. 求平方

l = [1,11,22,43,55]

l = [1,11,22,43,55]
l2 = map(lambda n: n**n,l)
for i in l2:print(i)
View Code

3. 过滤大于 15 的数

l = [1,11,22,43,55]

l = [1,11,22,43,55]
l2 = filter(lambda x:x>15,l)
for i in l2:print(i)
View Code

4. 按照 value 排序从大到小排序

dic = {'k1':10,'k2':20,'k3':30,'k4':12}

dic = {'k1':10,'k2':20,'k3':30,'k4':12}
print(sorted(dic,key=lambda key: dic[key],reverse=True))
View Code

5. 以下元祖一一对应组成列表中嵌套字典

x = (('a'),('b'))
z = (('c'),('d'))

x = (('a'),('b'))
z = (('c'),('d'))
print(list(map(lambda x: {x[0]:x[1]},zip(x,z))))
View Code

 

posted @ 2020-08-03 20:50  闫世成  阅读(116)  评论(0编辑  收藏  举报