Python基础(二)——常用内置函数

╰半橙微兮° 2021-10-29 08:52 537阅读 0赞

1. 常用内置函数

(1)isinstance(object, classinfo)

  用于判断一个对象是否为某一类型。

  • object 是实例对象
  • classinfo 是基本类型如 int, float 或者是类名或者是由它们组成的元组。

    print(isinstance(1, (int, str, float))) #True。实例 + 元组
    print(isinstance(‘2323’, dict)) #Flase 实例 + 基本类型

(2)type()

  •   type(Class) 输出。type(实例) 输出

(3)map(function, iterable)

  map(function, iterable) 产生一个将function应用于迭代对象中的所有元素并返回结果的迭代器。

  1. 1 from collections.abc import Iterator,Iterable
  2. 2
  3. 3 def test(x):
  4. 4 return x * 2
  5. 5
  6. 6 L = map(test, [1,2,3])
  7. 7
  8. 8 print(L) #<map object at 0x0000020C55F14390>
  9. 9 print(isinstance(L, Iterator)) #true
  10. 10 print(list(L)) #[2, 4, 6].list(iterable) list是一个构造器,其中的项与 iterable 中的项相同。
  11. 11
  12. 12 print(list(map(str, [1,2,3,3]))) #['1', '2', '3', '3']

  如上文所说,将 test() 函数应用于元素 1 * 2 = 2…..。其中第12行同第10行一致,注意通过list()函数将map()迭代器内容输出。

(4)reduce(function,iterable)

  官网给了个例子:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 等价于 ((((1+2)+3)+4)+5) 。这里划线部分其实就是个函数,这个函数是实现 x + y,将改函数应用于右边的 iterable,但是和map的区别就是,这个reduce有一个累加效果,也就是将上一步计算的结果当作下一步计算的参数,如下:

  1. 1 from functools import reduce
  2. 2 def sum(x, y):
  3. 3 return x + y
  4. 4
  5. 5 L = [1, 2, 3]
  6. 6 R = reduce(sum, L)
  7. 7 print(R) # 6

  即第六行sum函数需要两个参数,参数从L中取为1,2。送入sum计算得到3,然后3当作x,L中的3当作y,继续送入sum函数计算,得到3 + 3 = 6

  再看一个例子:

  1. 1 # 将字符串转成数字
  2. 2 from functools import reduce
  3. 3 dict = {
  4. '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
  5. 4
  6. 5 #'124' -> ((0*10+1)*10+2)*10+4
  7. 6 def char2numb(c):
  8. 7 return dict[c]
  9. 8
  10. 9 def calculate(x, y):
  11. 10 return x * 10 + y
  12. 11
  13. 12 13 def str2numb(s):
  14. 14 return reduce(calculate, list(map(char2numb, s))) #结合使用map很关键,char2numb函数应用到字符串上
  15. 15 print(str2numb('2323'))

(5)匿名函数

  匿名函数关键字是lambda,且函数不需要定义名称,比如:

  1. 1 def cube(y):
  2. 2 return y * y * y;
  3. 3
  4. 4
  5. 5 g = lambda x: x * x * x # 将匿名函数赋值给一个变量g,再利用变量来调用该函数
  6. 6 print(g(7))
  7. 7
  8. 8 print(cube(5))

  cube函数同g是相似的。lambda冒号前的是参数,可以多个,用逗号隔开,冒号右边是返回值

  lambda函数解和map和reduce一起使用:

  1. 1 li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
  2. 2 final_list = list(map(lambda x: x*2 , li))
  3. 3 print(final_list) #[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
  4. 1 from functools import reduce
  5. 2 li = [1, 2, 3]
  6. 3 sum = reduce((lambda x, y: x * y), li)
  7. 4 print (sum) # 6

  (个人觉得,也不是非lambda不可,是鸡肋吗?先在这埋下伏笔)

  lambda 在闭包中的使用,看详看第六点。

(6)闭包(点击查看)

(7)filter(function,iterable)

  用iterable中函数function返回真的那些元素,构建一个新的迭代器。官网上有两句话:①当function为None,则item for item in iterable if item。②当function不是None,item foritem in iterable if function(item)。

  1. 1 #①
  2. 2 print(list(filter(None,[0, 1, 33, False, None]))) # [1, 33]
  3. 3
  4. 4 #②
  5. 5 def test(x):
  6. 6 return x % 2 == 0
  7. 7 print(list(filter(test, [1,2,3,4]))) # [2, 4]
  8. 8
  9. 9 #又如
  10. 10 def not_empty(s):
  11. 11 return s and s.strip()
  12. 12 print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))) # ['A', 'B', 'C']

  通过例子很好理解,不过多解释。

  用filter筛选素数(廖雪峰网站):  

  1. 1 def _odd_iter():
  2. 2 n = 1
  3. 3 while True:
  4. 4 n = n + 2
  5. 5 yield n
  6. 6
  7. 7 def _not_divisible(n):
  8. 8 return lambda x: x % n > 0
  9. 9
  10. 10 def primes():
  11. 11 yield 2
  12. 12 it = _odd_iter() # 初始序列
  13. 13 while True:
  14. 14 n = next(it) # 返回序列的第一个数
  15. 15 yield n
  16. 16 it = filter(_not_divisible(n), it) # 构造新序列
  17. 17
  18. 18 # 打印1000以内的素数:
  19. 19 for n in primes():
  20. 20 if n < 1000:
  21. 21 print(n)
  22. 22 else:
  23. 23 break

  因为这段代码比较复杂,尤其是第16行,所以在上文先铺垫了①匿名函数②闭包③生成器

(8)sorted(iterable,*,key=None,reverse=False)

  根据iterable中的项,将项按照key(带有单个参数的函数)处理,处理之后排序。

  1. 1 print(sorted([-9, 0 ,89, 22])) # [-9, 0, 22, 89]
  2. 2
  3. 3 print(sorted([-9, 0, 22, 89], key=abs)) # [0, -9, 22, 89]
  4. 4
  5. 5 # 忽略大小写(因为阿斯克码)按首字母排序
  6. 6 print(sorted("This is a test string from Andrew".split(), key=str.lower))
  7. 7 #['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

  list.sort()的使用如[1, 2, 3, 1].sort()。但是效率没有sorted([1, 2, 3, 1])高。另一个区别是list.sort()只为列表定义,而sorted()可以用于任何迭代对象。

  1. 1 DICT = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
  2. 2 print(sorted(DICT, reverse=True)) # [5, 4, 3, 2, 1]

(9)enumerate(sequence,[start=0])

  此函数将一个可遍历对象组合成索引序列。一般用在 for 循环中

  1. 1 s = [4, 6, 7, 1]
  2. 2 for i in s:
  3. 3 print(i,end=' ')
  4. 4
  5. 5 print('\n', '=======')
  6. 6
  7. 7 for i in enumerate(s):
  8. 8 print(i, end='') # 输出 索引+值 的结构
  9. 9
  10. 10 print('\n', '=======')
  11. 11
  12. 12 for b,i in enumerate(s):
  13. 13 print(b,i,end='|')
  14. 14
  15. 15 print('\n', '=======')
  16. 16
  17. 17 for b,i in enumerate(s, 99): # 99为自定义索引开始值
  18. 18 print(b,i,end='|')

  输出结果:

  1. 1 4 6 7 1
  2. 2 =======
  3. 3 (0, 4)(1, 6)(2, 7)(3, 1)
  4. 4 =======
  5. 5 0 4| 1 6| 2 7| 3 1|
  6. 6 =======
  7. 7 99 4| 100 6| 101 7| 102 1|

  

2. 补充

(1) import VS from …. import

  看了例子就能清晰:   

  1. import sys
  2. print('命令行参数为:')
  3. for i in sys.argv:
  4. print(i)
  5. print('\n python 路径为',sys.path)
  6. from sys import argv, path
  7. print('命令行参数为:')
  8. for i in argv:
  9. print(i)
  10. print('\n python 路径为', path)

(2)函数可以被安插在“任何”地方(in Python everything is an object)

  这个怎么说呢,就是 Python 中的 function 真的无所不能,被用的神乎其神(我都被秀晕了QAQ),并不像 C/Java 中被固定的死死的,只能返回返回值被调用。至少学到现在,我发现Python中的函数不单单就是个函数,比如:

  1. 1 #函数嵌套函数
  2. 2 #嵌套在函数内部函数不能被外界调用,只能内部使用
  3. 3 def test(x, y):
  4. 4 def calculate(x):
  5. 5 return x * x
  6. 6 return calculate(x) + y
  7. 7 print(test(2, 2)) # 6
  8. 8
  9. 9
  10. 10 #函数可以元组中的一项
  11. 11 L = [test, '11'] #[<function test at 0x000001F196848A60>, '11']
  12. 12 print(L)
  13. 13 print(L[0](2, 2)) # 6
  14. 14 #最后一句就是取L的第一项[0],因为是test所以传入参数(2,2)
  15. 15
  16. 16
  17. 17 #函数可以赋值给变量
  18. 18 g = test
  19. 19 print(g(2, 2)) # 6. g 现在也就是test()复制品
  20. 20
  21. 21 #函数当作参数传入函数如上文map
  22. 1 # 函数可以当返回值
  23. 2 def test():
  24. 3 def test2():
  25. 4 print('1111')
  26. 5 return test2 #注意不是写成 test2().加了括号就是调用test2(),然后此句return回test2()给的return了。可看后面的例子
  27. 6 g = test()
  28. 7 print(g) # <function test.<locals>.test2 at 0x000002721DDB8AE8>
  29. 8
  30. 9
  31. 10 #例子
  32. 11 # def test():
  33. 12 # def test2():
  34. 13 # print('1111') # 1111
  35. 14 # return test2()
  36. 15 # print(test()) # None

以后遇到不断补充……

转载于:https://www.cnblogs.com/KongHuZi/p/10873927.html

发表评论

表情:
评论列表 (有 0 条评论,537人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python基础函数

    一、zip()函数 zip函数接受任意多个可迭代对象作为参数,将对象中对应的元素打包成一个tuple,然后返回一个可迭代的zip对象.这个可迭代对象可以使用循环的方式列出其