内置函数
# 查看所有的内置函数
import builtins
print(dir(builtins))
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', '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', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'execfile', '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', 'runfile', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
常用的内置函数如下;
- print():屏幕输出
- list():将一个可迭代对象转换成列表
- abs():返回绝对值
- set():创建一个无序不重复的元素集
- tuple():将一个可迭代对象转换成元组,(可迭代指的是可以 使用 for ... in ...)
- sum():求和
- min():求最小值
- map():可以对可迭代对象中的每一个元素进行映射,分别去执行
- zip():将可迭代对象作为参数,将对象中对应的元素打包成一个 元组
- reduce():对参数序列中的元素进行累积
示例
zip拉链函数
# zip() 拉链函数,将对象中对应的元素打包成一个个元组,然后返回由这些元素组成的内容
a = [1, 2, 3]
b = [4, 5, 6]
c = zip(a, b) # c 是一个 zip 对象 (迭代器)
print(type(c))
print(tuple(c)) # 消耗了迭代器,生成了元组:((1, 4), (2, 5), (3, 6))
print(list(c)) # 再次尝试消耗迭代器, 此时迭代器已经空了,输出:[]
<zip object at 0x000001C42FDA5340>
<class 'zip'>
((1, 4), (2, 5), (3, 6))
[]
为什么不能直接打印输出
c
呢?以及为什么list(c)
的输出是一个空列表呢?
代码中涉及到的核心问题是
zip()
函数返回的是一个迭代器
。
1、
zip(a, b)
返回一个zip
对象,这是一种迭代器。迭代器本身不保存数据,它是一个惰性对象
,在需要时生成每个元素。直接打印c
,你只会看到类似<zip object at 0x000001C42FDA5340>
,这表示是一个zip
对象,而不是具体的数据。
2、为什么使用
list(c)
第二次会得到一个空列表?
这涉及到
迭代器的一次性
特性。
一次性特性:
zip
对象是一个迭代器,迭代器只能被遍历一次。①、第一次调用
tuple(c)
时,迭代器已经被完全消耗掉了,将所有内容 “取走” 用于生成元组。②、第二次调用
list(c)
时,迭代器已经空了,所以得到的是一个空列表。
如果你需要多次使用zip的结果,有两种常见方法:
1、转换为列表或元组后存储。
将 zip 结果立即转为列表或元组存储,这样可以多次使用:
c = list(zip(a, b)) # 或者 tuple(zip(a, b))
print(c) # [(1, 4), (2, 5), (3, 6)]
print(tuple(c)) # ((1, 4), (2, 5), (3, 6))
2、重新创建迭代器
如果需要重复使用 zip 对象,聂可以重新创建它:
c = zip(a, b)
print(tuple(c)) # ((1, 4), (2, 5), (3, 6))
c = zip(a, b) # 重新创建 zip 对象
print(list(c)) # [(1, 4), (2, 5), (3, 6)]
map()函数
map(function, iterable) 映射函数
作用:可对可迭代对象中的每一个元素进行映射,分别执行function。
li = [1, 2, 3, 4]
# 定义一个:传入一个数,返回这个数的平方的函数
def func(x):
return x**2
np = map(func, li)
print(list(np)) # 转换为列表输出
[1, 4, 9, 16]
# 匿名函数方式 Lambda
print(list(map(lambda x: x**2, li)))
reduce()函数
reduce(function, iterable):减少,降低可迭代对象元素的一个操作
对
参数
序列中的元素进行归约
,将可迭代对象中的元素进行减少的一个操作。注意这句话的意思:reduce() 其中之一的参数必是一个 序列。
**Python中的序列的定义:是指那些可以通过
索引
来访问其元素、并支持切片操作的
的数据结构。**按照这个定义,元组
、列表
和字符串
都属于序列类型,而 集合 和 字典则不属于(也即:集合和字典是无序的,不能通过索引下标的方式来访问)。
st = 'abcefg'
t = (1, 2, 3)
li = [1, 2, 3, 4]
# 定义一个两个数相加的函数
def func(x, y):
return x + y
from functools import reduce # 需要导入模块
print(reduce(func, st))
print(reduce(func, t))
print(reduce(func, li))
abcefg
6
10
enumerate()
用于将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标,一般用在for循环中。
enumerate(可迭代对象, [start=0])
li = ['a', 'b', 'c', 'd']
for i,j in enumerate(li): # enumerate 会返回 数据和数据下标 两个值
print(i,j)
0 a
1 b
2 c
3 d