2022年 11月 4日

python 内建函数

一、python 三元表达式

  1. x = 1
  2. y = 2
  3. r = x if x < y else y
  4. print("r=",r)

Python 内建函数主要分为:filter() map() reduce() zip()

1.filter

a = [1,2,3,4,5,6,7]
print(list(filter(lambda x:x<5,a)))

2.map

a = [1,2,3,4,5,6,7]
print(map(lambda x:x,a))
print(list(map(lambda x:x,a)))
print(list(map(lambda x:x*x,a)))
a = [1,2,3,4,5,6,7]
b = [1,1,1,1,1,1,1]
print(list(map(lambda x,y:x+y,a,b)))
  1. list_x = [1,2,3,4,5,6,7,8]
  2. def squre(x):
  3. return x*x
  4. #不采用map 的方式
  5. #########################################
  6. list_xx=[]
  7. for v in list_x:
  8. list_xx.append(squre(v))
  9. for v in list_xx:
  10. print(v,end=' ')
  11. print('\n')
  12. #######################################
  13. #采用map的方式进行
  14. list_xx = list(map(squre,list_x))
  15. print(list_xx)

reduce

from functools import reduce
print(reduce(lambda x,y:x+y,[2,3,4],1))  # (1+2)+3+4

zip

zip((1,2,3),(4,5,6))
for i in zip((1,2,3),(4,5,6)):
    print(i)


dicta = {'a':'aa','b':'bb'}
dictb = zip(dicta.values(),dicta.keys())
print(dict(dictb))