欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python学习笔记(三):常用内置函数学习

程序员文章站 2022-05-30 12:12:14
...
一.如何查看Python3的所有内置函数
命令:dir(__builtins__)
效果如下:
dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',

'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',

'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',

'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError',

'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError',

'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',

'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',

'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError',

'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError',

'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError',

'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError',

'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',

'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',

'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',

'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError',

'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__',

'__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii',

'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile',

'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate',

'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals',

'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',

'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',

'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',

'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',

'super', 'tuple', 'type', 'vars', 'zip']

二.如何使用内置函数.
help(内置函数) 或者百度或者Google

三.常用内置函数介绍。
1.chr和ord

help(chr)
Help on built-in function chr in module builtins:

chr(...)
    chr(i) -> Unicode character
    
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

chr只有一个ordinal参数,并且范围是[0,10FFFF]

功能:将参数i转换为Unicode 字符
In [1]: chr(0)
Out[1]: '\x00'

In [2]: chr(0x31)
Out[2]: '1'

In [3]: chr(65)
Out[3]: 'A'

In [4]: chr(20013)
Out[4]: '中'



>>> help(ord)
Help on built-in function ord in module builtins:

ord(...)
    ord(c) -> integer
    
    Return the integer ordinal of a one-character string.

chr只有一个ordinal参数,并且必须是单个字符

功能:将Unicode 字符转换为整数

In [6]: ord('0')
Out[6]: 48

In [7]: ord('A')
Out[7]: 65

In [8]: ord('a')
Out[8]: 97

In [9]: ord('中')
Out[9]: 20013




2.min和max

>>> help(min)
Help on built-in function min in module builtins:

min(...)
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.

两种函数形式,参数可以是迭代器,也可以至少两个参数,返回最小的一个
功能:返回参数里最小的一个对象。

In [11]: min('a','b','c')   #必须是同一类型的参数
Out[11]: 'a'

In [12]: min(-5,-100,99,25)
Out[12]: -100

In [13]: list = [1,3,5,7,9,-11]

In [14]: min(list)   #参数是可迭代的对象
Out[14]: -11

In [15]: min(-5,-100,99,25,key = abs)  #可以指定方式比较
Out[15]: -5

In [16]: min(-5,-100,99,25,key = lambda x:x**2)  #包含lambda语句
Out[16]: -5




>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

参数和min函数是一样的,求最大值。

In [17]: max('a','b','c')  #必须是同一类型的参数
Out[17]: 'c'

In [18]: max(-5,-100,99,25)
Out[18]: 99

In [19]: list = [1,3,5,7,9,-11]

In [20]: max(list)   #参数是可迭代的对象
Out[20]: 9

In [21]: max(-5,-100,99,25,key = abs)  #可以指定方式比较
Out[21]: -100

In [22]: max(-5,-100,99,25,key = lambda x:x**2)  #包含lambda语句
Out[22]: -100




3.bin、hex和oct

>>> help(bin)
Help on built-in function bin in module builtins:

bin(...)
    bin(number) -> string
    
    Return the binary representation of an integer.
    
       >>> bin(2796202)
       '0b1010101010101010101010'

将一个integer转换为二进制形式,返回字符串。

In [23]: bin(7)
Out[23]: '0b111'

In [24]: bin(123)
Out[24]: '0b1111011'

In [25]: bin(2796202)
Out[25]: '0b1010101010101010101010'



>>> help(oct)
Help on built-in function oct in module builtins:

oct(...)
    oct(number) -> string
    
    Return the octal representation of an integer.
    
       >>> oct(342391)
       '0o1234567'

将一个integer转换为八进制形式,返回字符串

In [26]: oct(7)
Out[26]: '0o7'

In [27]: oct(8)
Out[27]: '0o10'

In [28]: oct(123)
Out[28]: '0o173'

In [29]: oct(342391)
Out[29]: '0o1234567'





>>> help(hex)
Help on built-in function hex in module builtins:

hex(...)
    hex(number) -> string
    
    Return the hexadecimal representation of an integer.
    
       >>> hex(3735928559)
       '0xdeadbeef'

将一个integer转换为十六进制形式,返回字符串

In [30]: hex(7)
Out[30]: '0x7'

In [31]: hex(123)
Out[31]: '0x7b'

In [32]: hex(15)
Out[32]: '0xf'

In [33]: hex(3735928559)
Out[33]: '0xdeadbeef'




4.abs和sum
>>> help(abs)
Help on built-in function abs in module builtins:

abs(...)
    abs(number) -> number
    
    Return the absolute value of the argument.

求绝对值


In [38]: abs(5)
Out[38]: 5

In [39]: abs(-5)
Out[39]: 5

In [40]: abs(0)
Out[40]: 0

In [41]: abs(-567)
Out[41]: 567

In [42]: abs(-56.7)
Out[42]: 56.7




>>> help(sum)
Help on built-in function sum in module builtins:

sum(...)
    sum(iterable[, start]) -> value
    
    Return the sum of an iterable of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the iterable is
    empty, return start.

sum的参数是一个可迭代对象。而且可迭代器对象里的item不能是字符串,必须是数字。

In [45]: L = [1,2,3,4,5]

In [46]: sum(L)
Out[46]: 15

In [47]: T = 1,2,3,4,5

In [48]: sum(T)
Out[48]: 15

In [49]: S = {1,2,3,4,5}

In [50]: sum(S)
Out[50]: 15

In [51]: sum(S,2)
Out[51]: 17

In [52]: sum(S,-2)
Out[52]: 13





5.divmod、pow和round
>>> help(divmod)
Help on built-in function divmod in module builtins:

divmod(...)
    divmod(x, y) -> (div, mod)
    
    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.

两个参数,返回商和余数(tuple类型)

In [57]: divmod(12,3.2)
Out[57]: (3.0, 2.3999999999999995)

In [58]: divmod(12,3)
Out[58]: (4, 0)

In [59]: divmod(12,5)
Out[59]: (2, 2)

In [60]: divmod(5,12)
Out[60]: (0, 5)

In [61]: divmod(12,3.5)
Out[61]: (3.0, 1.5)

In [62]: divmod(12,3.7)
Out[62]: (3.0, 0.8999999999999995)

In [63]: divmod(12.6,3.7)
Out[63]: (3.0, 1.4999999999999991)




>>> help(pow)
Help on built-in function pow in module builtins:

pow(...)
    pow(x, y[, z]) -> number
    
    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for ints).

如果是2个参数,则返回X的Y次方
如果是3个参数,则返回X的Y次方 除以 Z 的余数
三个参数都必须是整数

In [64]: pow(2,2,3)    #2*2 % 3 = 1
Out[64]: 1

In [65]: pow(2,2)  # 2*2 = 4
Out[65]: 4

In [66]: pow(2,5)  # 2*2*2*2*2 = 32
Out[66]: 32

In [67]: pow(2,5,6)  # 2*2*2*2*2 % 6 = 2
Out[67]: 2




>>> help(round)
Help on built-in function round in module builtins:

round(...)
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.

四舍五入,可指定精度,默认取整

In [70]: round(1.23)
Out[70]: 1

In [71]: round(1.56)
Out[71]: 2

In [72]: round(1.56789,3)
Out[72]: 1.568

In [73]: round(1.56789,6)
Out[73]: 1.56789

In [74]: round(1.56789,8)
Out[74]: 1.56789

In [75]: round(1.56789,-8)
Out[75]: 0.0

In [76]: round(2/3,6)
Out[76]: 0.666667




6.all和any

>>> help(all)
Help on built-in function all in module builtins:

all(...)
    all(iterable) -> bool
    
    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.
参数:迭代器。
包含0值,返回False,否则返回True
迭代器为空,返回True

In [77]: L = [1,3,2,7,9,0]

In [78]: all(L)
Out[78]: False

In [79]: L = [1,3,2,7,9]

In [80]: all(L)
Out[80]: True

In [81]: L = [1,3,2,7,9,None]

In [82]: all(L)
Out[82]: False

In [83]: L = [1,3,2,7,9,'']

In [84]: all(L)
Out[84]: False

In [85]: L = [1,3,2,7,9,' ']

In [86]: all(L)
Out[86]: True

In [87]: L = []

In [88]: all(L)   #迭代器为空,返回True
Out[88]: True




>>> help(any)
Help on built-in function any in module builtins:

any(...)
    any(iterable) -> bool
    
    Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.

参数:迭代器。
包含非0值,返回True,否则返回False
迭代器为空,返回False

In [96]: L = ['',2,3]

In [97]: any(L)
Out[97]: True

In [98]: L = ['',[],{}]

In [99]: any(L)
Out[99]: False

In [100]: L = ['',[],{},'0']

In [101]: any(L)
Out[101]: True

In [102]: L = ['',[],{},0]

In [103]: any(L)
Out[103]: False






7.ascii
>>> help(ascii)
Help on built-in function ascii in module builtins:

ascii(...)
    ascii(object) -> string
    
    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \x, \u or \U escapes.  This generates a string similar
    to that returned by repr() in Python 2.

返回对象的可打印表字符串表现方式

In [104]: ascii('!')
Out[104]: "'!'"

In [105]: ascii(1)
Out[105]: '1'

In [106]: ascii('1')
Out[106]: "'1'"

In [107]: ascii(123456)
Out[107]: '123456'

In [108]: ascii('中国')
Out[108]: "'\\u4e2d\\u56fd'"

In [109]: ascii('\n')
Out[109]: "'\\n'"

IIn [110]: ascii('□')
Out[110]: "'\\u25a1'"

InIn [112]: ascii('×')
Out[112]: "'\\xd7'"

In [113]: print ('\xd7')
×




8.input
>>> help(input)
Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string
    
    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

input:读取用户输入值,返回字符串。

In [114]: input()
123
Out[114]: '123'

In [115]: input()
哈哈哈哈哈
Out[115]: '哈哈哈哈哈'

In [116]: input("Please Enter text:")
Please Enter text:hello world!
Out[116]: 'hello world!'



9.callable
>>> help(callable)
Help on built-in function callable in module builtins:

callable(...)
    callable(object) -> bool
    
    Return whether the object is callable (i.e., some kind of function).
    Note that classes are callable, as are instances of classes with a
    __call__() method.

判断某对象是否可被调用

In [1]: callable(abs)
Out[1]: True

In [2]: callable(map)
Out[2]: True

In [3]: def sayhello():
   ...:     print ("hello")
   ...:

In [4]: callable(sayhello)
Out[4]: True

In [5]: callable('abc')
Out[5]: False

In [6]: callable(5)
Out[6]: False

In [7]: class A:
   ...:     def __init__(self,value):
   ...:         self.value = value
   ...:

In [8]: callable(A)
Out[8]: True




10.删除对象的某个属性
help(delattr)
Help on built-in function delattr in module builtins:

delattr(...)
    delattr(object, name)
    
    Delete a named attribute on an object; delattr(x, 'y') is equivalent to
    ``del x.y''.


In [19]: class A:
    ...:     def __init__(self,value):
    ...:         self.value = value
    ...:

In [20]: a = A('5')

In [21]: a.value
Out[21]: '5'

In [22]: delattr(a,'value')

In [23]: a.value   #属性已删除,所以报错。
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-669656c3105a> in <module>()
----> 1 a.value

AttributeError: 'A' object has no attribute 'value'




11.enumerate
>>> help(enumerate)
Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.


根据可迭代对象创建枚举对象
In [1]: L = [1,2,3,4,5,6,7,8,9]

In [2]: for index,value in enumerate(L):
   ...:     print (index,value)
   ...:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

In [3]: for index,value in enumerate(L,start = 5):   #也可以指定起始索引
   ...:     print (index,value)
   ...:
5 1
6 2
7 3
8 4
9 5
10 6
11 7
12 8
13 9



12.eval
>>> help(eval)
Help on built-in function eval in module builtins:

eval(...)
    eval(source[, globals[, locals]]) -> value
    
    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

表达式求值。

In [7]: eval('1+2*6')
Out[7]: 13

In [8]: eval('abs(-5)')
Out[8]: 5

13.exec
>>> help(exec)
Help on built-in function exec in module builtins:

exec(...)
    exec(object[, globals[, locals]])
    
    Read and execute code from an object, which can be a string or a code
    object.
    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.

执行动态语句块

In [12]: exec('a = 1 + 1')

In [13]: a
Out[13]: 2




14.zip
>>> help(zip)
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器

In [14]: a = [1,2,3,4,5]

In [15]: b = ['a','b','c','d','e','f']

In [16]: for i in zip(a,b):
    ...:     print (i)
    ...:
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')


相关标签: Python