2.4 Python常用内置函数用法精要
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',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'WindowsError',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'all',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'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',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
2.4.1 类型转换与类型判断
- 进制转换
print(bin(555)) #把数字转换为二进制串
print(oct(555)) #把数字转换为八进制串
print(hex(555)) #把数字转换为十六进制串
0b1000101011
0o1053
0x22b
- int()函数
print(int(-3.2)) #实转整
print(int('22b',16)) #十六进制转十进制
print(int('111',6)) #第二个参数可以为2-36之间的数字
print(int('0b111',0)) #0表示使用字符串隐含的进制
-3
555
43
7
print(int('0b111')) #非十进制字符串间,必须制定第二个参数
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-55a62c174b12> in <module>
----> 1 print(int('0b111')) #非十进制字符串间,必须制定第二个参数
ValueError: invalid literal for int() with base 10: '0b111'
-
float() #其他类型转实数
-
ord()与chr()
print(ord('a'))
print(chr(65))
print(ord('中'))
97
A
20013
-
str()
-
ascii() #把对象转换为ASCII码表示形式
print(ascii('a'))
print(ascii('中文'))
'a'
'\u4e2d\u6587'
-
内置类bytes(详见p30)
-
list()、tuple()、dict()、set()、frozenset()
-
type()和isinstance()
print(isinstance(3j,(int,float,complex)))
True
2.4.2 最值与求和
print(max(['2','111'])) #不指定排序规则,默认为ASCII码的大小
2
2.4.3 基本输入输出
-
input() 中内容一律作为字符串对待
-
print()
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
2.4.4 排序与逆序
- sorted() #返回新列表
import random
x = list(range(11))
random.shuffle(x)
print(x)
print(sorted(x))
print(x) #sorted()不影响原列表
[8, 2, 6, 10, 0, 9, 7, 3, 4, 1, 5]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[8, 2, 6, 10, 0, 9, 7, 3, 4, 1, 5]
help(sorted) #key为转换类型(转换为该类型后进行排序),默认False为升序
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
2.4.5 枚举
- enumerate()
print(list(enumerate('abcdefg'))) #枚举字符串中的元素
print(list(enumerate(['Python','Greate']))) #枚举列表中的元素
print(list(enumerate({'a':97,'b':98,'c':99}.items()))) #枚举列表中所有元素,若无“.items()”,则只取出key值
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]
[(0, 'Python'), (1, 'Greate')]
[(0, ('a', 97)), (1, ('b', 98)), (2, ('c', 99))]
for index,value in enumerate(range(10,15)): #枚举range中的对象
print((index,value),end=' ')
(0, 10) (1, 11) (2, 12) (3, 13) (4, 14)
help(enumerate) #参数start用来指定枚举时的索引起始值
Help on class enumerate in module builtins:
class enumerate(object)
| enumerate(iterable, start=0)
|
| Return an enumerate object.
|
| iterable
| an object supporting 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).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
2.4.6 map()、reduce()、filter()
- map()
from random import randint
x = randint(1,1e30)
y = list(map(int,str(x))) #提取大整数每位上的数字
print(y)
[2, 8, 2, 4, 0, 9, 6, 5, 9, 5, 8, 3, 9, 8, 0, 8, 7, 0, 1, 6, 9, 8, 7, 1, 2, 2, 8, 5, 6, 5]
- reduce()
def add(x,y):
return x+y
from functools import reduce
seq = list(range(1,10))
print(reduce(add,seq))
45
- filter() #将一个单参数函数作用到一个序列上,返回该序列中使得该函数返回值为True的那些元素组成的filter对象
- 如果制定函数为None,则返回序列中等价于True的元素
seq = ['fool','x41','?! ','***']
def func(x):
return x.isalnum()
a = filter(func,seq)
print(type(a))
print(list(a))
print(seq) #不对原列表做任何修改
<class 'filter'>
['fool', 'x41']
['fool', 'x41', '?! ', '***']
2.4.7 range()
-
range(start, stop[, step]) #[start,stop)
-
在循环结构中经常使用range()函数来控制循环次数
for i in range(4):
print(3,end=' ')
3 3 3 3
- 使用range()函数控制数值范围
for i in range(200,0,-1):
if i %17 == 0:
print(i) #200以内能被17整除的最大正整数
break
187
2.4.8 zip()
print(list(zip('abcd'))) #压缩一个序列
print(list(zip('123','abc','!@?'))) #压缩三个序列
for item in zip ('abcd',range(3)): #zip对象可迭代
print(item)
[('a',), ('b',), ('c',), ('d',)]
[('1', 'a', '!'), ('2', 'b', '@'), ('3', 'c', '?')]
('a', 0)
('b', 1)
('c', 2)