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

谁借莪1个温暖的怀抱¢ 2022-06-08 04:58 486阅读 0赞

一.如何查看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 字符

  1. In [1]: chr(0)
  2. Out[1]: '\x00'
  3. In [2]: chr(0x31)
  4. Out[2]: '1'
  5. In [3]: chr(65)
  6. Out[3]: 'A'
  7. In [4]: chr(20013)
  8. 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 字符转换为整数

  1. In [6]: ord('0')
  2. Out[6]: 48
  3. In [7]: ord('A')
  4. Out[7]: 65
  5. In [8]: ord('a')
  6. Out[8]: 97
  7. In [9]: ord('中')
  8. 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.

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

  1. In [11]: min('a','b','c') #必须是同一类型的参数
  2. Out[11]: 'a'
  3. In [12]: min(-5,-100,99,25)
  4. Out[12]: -100
  5. In [13]: list = [1,3,5,7,9,-11]
  6. In [14]: min(list) #参数是可迭代的对象
  7. Out[14]: -11
  8. In [15]: min(-5,-100,99,25,key = abs) #可以指定方式比较
  9. Out[15]: -5
  10. In [16]: min(-5,-100,99,25,key = lambda x:x**2) #包含lambda语句
  11. 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函数是一样的,求最大值。

  1. In [17]: max('a','b','c') #必须是同一类型的参数
  2. Out[17]: 'c'
  3. In [18]: max(-5,-100,99,25)
  4. Out[18]: 99
  5. In [19]: list = [1,3,5,7,9,-11]
  6. In [20]: max(list) #参数是可迭代的对象
  7. Out[20]: 9
  8. In [21]: max(-5,-100,99,25,key = abs) #可以指定方式比较
  9. Out[21]: -100
  10. In [22]: max(-5,-100,99,25,key = lambda x:x**2) #包含lambda语句
  11. 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转换为二进制形式,返回字符串。

  1. In [23]: bin(7)
  2. Out[23]: '0b111'
  3. In [24]: bin(123)
  4. Out[24]: '0b1111011'
  5. In [25]: bin(2796202)
  6. 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转换为八进制形式,返回字符串

  1. In [26]: oct(7)
  2. Out[26]: '0o7'
  3. In [27]: oct(8)
  4. Out[27]: '0o10'
  5. In [28]: oct(123)
  6. Out[28]: '0o173'
  7. In [29]: oct(342391)
  8. 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转换为十六进制形式,返回字符串

  1. In [30]: hex(7)
  2. Out[30]: '0x7'
  3. In [31]: hex(123)
  4. Out[31]: '0x7b'
  5. In [32]: hex(15)
  6. Out[32]: '0xf'
  7. In [33]: hex(3735928559)
  8. 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.

求绝对值

  1. In [38]: abs(5)
  2. Out[38]: 5
  3. In [39]: abs(-5)
  4. Out[39]: 5
  5. In [40]: abs(0)
  6. Out[40]: 0
  7. In [41]: abs(-567)
  8. Out[41]: 567
  9. In [42]: abs(-56.7)
  10. 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不能是字符串,必须是数字。

  1. In [45]: L = [1,2,3,4,5]
  2. In [46]: sum(L)
  3. Out[46]: 15
  4. In [47]: T = 1,2,3,4,5
  5. In [48]: sum(T)
  6. Out[48]: 15
  7. In [49]: S = {1,2,3,4,5}
  8. In [50]: sum(S)
  9. Out[50]: 15
  10. In [51]: sum(S,2)
  11. Out[51]: 17
  12. In [52]: sum(S,-2)
  13. 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类型)

  1. In [57]: divmod(12,3.2)
  2. Out[57]: (3.0, 2.3999999999999995)
  3. In [58]: divmod(12,3)
  4. Out[58]: (4, 0)
  5. In [59]: divmod(12,5)
  6. Out[59]: (2, 2)
  7. In [60]: divmod(5,12)
  8. Out[60]: (0, 5)
  9. In [61]: divmod(12,3.5)
  10. Out[61]: (3.0, 1.5)
  11. In [62]: divmod(12,3.7)
  12. Out[62]: (3.0, 0.8999999999999995)
  13. In [63]: divmod(12.6,3.7)
  14. 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 的余数
三个参数都必须是整数

  1. In [64]: pow(2,2,3) #2*2 % 3 = 1
  2. Out[64]: 1
  3. In [65]: pow(2,2) # 2*2 = 4
  4. Out[65]: 4
  5. In [66]: pow(2,5) # 2*2*2*2*2 = 32
  6. Out[66]: 32
  7. In [67]: pow(2,5,6) # 2*2*2*2*2 % 6 = 2
  8. 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.

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

  1. In [70]: round(1.23)
  2. Out[70]: 1
  3. In [71]: round(1.56)
  4. Out[71]: 2
  5. In [72]: round(1.56789,3)
  6. Out[72]: 1.568
  7. In [73]: round(1.56789,6)
  8. Out[73]: 1.56789
  9. In [74]: round(1.56789,8)
  10. Out[74]: 1.56789
  11. In [75]: round(1.56789,-8)
  12. Out[75]: 0.0
  13. In [76]: round(2/3,6)
  14. 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

  1. In [77]: L = [1,3,2,7,9,0]
  2. In [78]: all(L)
  3. Out[78]: False
  4. In [79]: L = [1,3,2,7,9]
  5. In [80]: all(L)
  6. Out[80]: True
  7. In [81]: L = [1,3,2,7,9,None]
  8. In [82]: all(L)
  9. Out[82]: False
  10. In [83]: L = [1,3,2,7,9,'']
  11. In [84]: all(L)
  12. Out[84]: False
  13. In [85]: L = [1,3,2,7,9,' ']
  14. In [86]: all(L)
  15. Out[86]: True
  16. In [87]: L = []
  17. In [88]: all(L) #迭代器为空,返回True
  18. 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

  1. In [96]: L = ['',2,3]
  2. In [97]: any(L)
  3. Out[97]: True
  4. In [98]: L = ['',[],{}]
  5. In [99]: any(L)
  6. Out[99]: False
  7. In [100]: L = ['',[],{},'0']
  8. In [101]: any(L)
  9. Out[101]: True
  10. In [102]: L = ['',[],{},0]
  11. In [103]: any(L)
  12. 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.

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

  1. In [104]: ascii('!')
  2. Out[104]: "'!'"
  3. In [105]: ascii(1)
  4. Out[105]: '1'
  5. In [106]: ascii('1')
  6. Out[106]: "'1'"
  7. In [107]: ascii(123456)
  8. Out[107]: '123456'
  9. In [108]: ascii('中国')
  10. Out[108]: "'\\u4e2d\\u56fd'"
  11. In [109]: ascii('\n')
  12. Out[109]: "'\\n'"
  13. IIn [110]: ascii('□')
  14. Out[110]: "'\\u25a1'"
  15. InIn [112]: ascii('×')
  16. Out[112]: "'\\xd7'"
  17. In [113]: print ('\xd7')
  18. ×

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:读取用户输入值,返回字符串。

  1. In [114]: input()
  2. 123
  3. Out[114]: '123'
  4. In [115]: input()
  5. 哈哈哈哈哈
  6. Out[115]: '哈哈哈哈哈'
  7. In [116]: input("Please Enter text:")
  8. Please Enter text:hello world!
  9. 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.

判断某对象是否可被调用

  1. In [1]: callable(abs)
  2. Out[1]: True
  3. In [2]: callable(map)
  4. Out[2]: True
  5. In [3]: def sayhello():
  6. ...: print ("hello")
  7. ...:
  8. In [4]: callable(sayhello)
  9. Out[4]: True
  10. In [5]: callable('abc')
  11. Out[5]: False
  12. In [6]: callable(5)
  13. Out[6]: False
  14. In [7]: class A:
  15. ...: def __init__(self,value):
  16. ...: self.value = value
  17. ...:
  18. In [8]: callable(A)
  19. 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’’.

  1. In [19]: class A:
  2. ...: def __init__(self,value):
  3. ...: self.value = value
  4. ...:
  5. In [20]: a = A('5')
  6. In [21]: a.value
  7. Out[21]: '5'
  8. In [22]: delattr(a,'value')
  9. In [23]: a.value #属性已删除,所以报错。
  10. ---------------------------------------------------------------------------
  11. AttributeError Traceback (most recent call last)
  12. <ipython-input-23-669656c3105a> in <module>()
  13. ----> 1 a.value
  14. 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.

根据可迭代对象创建枚举对象

  1. In [1]: L = [1,2,3,4,5,6,7,8,9]
  2. In [2]: for index,value in enumerate(L):
  3. ...: print (index,value)
  4. ...:
  5. 0 1
  6. 1 2
  7. 2 3
  8. 3 4
  9. 4 5
  10. 5 6
  11. 6 7
  12. 7 8
  13. 8 9
  14. In [3]: for index,value in enumerate(L,start = 5): #也可以指定起始索引
  15. ...: print (index,value)
  16. ...:
  17. 5 1
  18. 6 2
  19. 7 3
  20. 8 4
  21. 9 5
  22. 10 6
  23. 11 7
  24. 12 8
  25. 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.

执行动态语句块

  1. In [12]: exec('a = 1 + 1')
  2. In [13]: a
  3. 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.

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

  1. In [14]: a = [1,2,3,4,5]
  2. In [15]: b = ['a','b','c','d','e','f']
  3. In [16]: for i in zip(a,b):
  4. ...: print (i)
  5. ...:
  6. (1, 'a')
  7. (2, 'b')
  8. (3, 'c')
  9. (4, 'd')
  10. (5, 'e')

发表评论

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

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

相关阅读