zoukankan      html  css  js  c++  java
  • Python基础(二)——常用内置函数

    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) 输出<class 'type'>。type(实例) 输出 <class '类名'>

    (3)map(function, iterable)

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

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

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

      再看一个例子:

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

    (5)匿名函数

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

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

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

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

    1 li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
    2 final_list = list(map(lambda x: x*2 , li)) 
    3 print(final_list)  #[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
    1 from functools import reduce
    2 li = [1, 2, 3]
    3 sum = reduce((lambda x, y: x * y), li)
    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 #
     2 print(list(filter(None,[0, 1, 33, False, None]))) # [1, 33]
     3 
     4 #
     5 def test(x):
     6     return x % 2 == 0
     7 print(list(filter(test, [1,2,3,4]))) # [2, 4]
     8 
     9 #又如
    10 def not_empty(s):
    11     return s and s.strip()
    12 print(list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))) # ['A', 'B', 'C']

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

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

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

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

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

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

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

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

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

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

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

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

      输出结果:

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

      

    2. 补充

    (1) import VS from .... import

      看了例子就能清晰:   

    import sys
    print('命令行参数为:')
    for i in sys.argv:
        print(i)
    print('
     python 路径为',sys.path)
    from sys import argv, path
    print('命令行参数为:')
    for i in  argv:
        print(i)
    print('
     python 路径为', path)

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

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

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

    以后遇到不断补充......

  • 相关阅读:
    如何关闭和打开oracle 10g自动收集统计信息功能
    ORA00600:internal error code,arguments
    ORA01033: ORACLE initialization or shutdown in progress
    ORA01652:unable to extend temp segment by num in tablespace name
    ORA01578:Oracle data block corrupted
    ORA03113:endoffile on communication channel
    ORA01650:unable to extend rollback segment NAME by NUM intablespace NAME
    ORA01628:max # of extents num reached for rollback segment num
    C# 项目中的 bin 目录和 obj 目录的区别,以及 Debug 版本和 Release 版本的区别
    管理 Hadoop 集群的5大工具
  • 原文地址:https://www.cnblogs.com/KongHuZi/p/10873927.html
Copyright © 2011-2022 走看看