第 7 章 内置函数

所谓内置函数,就是Python解释器已经拥有的一系列函数和类型,这些函数一直可用,无需定义。

7.1 dict函数

7.1.1 描述

dict() 函数用于创建一个字典。

7.1.2 语法

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

参数说明:

**kwargs -- 关键字
mapping -- 元素的容器。
iterable -- 可迭代对象。

7.1.3 返回值

返回一个字典。

7.1.4 实例

以下实例展示了 dict 的使用方法:

>>>dict()                        # 创建空字典
{}
>>> dict(a='a', b='b', t='t')     # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3]))   # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)])    # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>>

7.2 zip函数

7.2.1 描述

将不同迭代对象中的元素整合为一个迭代对象。

7.2.2 语法

zip(*iterables)

7.2.3 返回值

返回元组。

7.2.4 特殊用法

zip()方法和*运算符连用时,用来拆解一个列表。

7.2.5 实例

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True

7.3 list函数

7.3.1 描述

与其说list()是函数,不如说它是一个可变序列的数据类型,其作用是将数据转化为列表。

7.3.2 语法

class list([iterable])

7.3.3 返回值

可变序列

7.3.4 实例

>>> list('world')
['w', 'o', 'r', 'l', 'd']

7.4 min函数

7.4.1 描述

求多个参数中的最小值,或者是可迭代数据中的最小元素。

7.4.2 语法

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

7.4.3 返回值

最小的元素,可能是字符串、数字,也可能是元组、列表。

7.4.4 实例

>>> min(1,2,3)  # 求三个元素中的最小值
1
>>> min(1,'2') # 不同类型的变量无法直接求最小值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>> min('2','3') # 可以对字符串求最小值,按字母顺序求值
'2'
>>> min(-1,-2) # 可以对负数求最小值
-2
>>> min(-1,-2,key = abs) # key参数可以是函数,例如abs()
-1
>>> min(-1,'-2',key = int) # key参数为类型转换函数
'-2'
>>> min([1,2],(1,1)) # 无法直接对元素和列表求最小值
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'tuple' and 'list'
>>> min([1,2],(1,1),key = lambda x:x[1]) # key值可以是列表中的某个元素
(1, 1)
>>> min([1,2],(1,3),key = lambda x:x[1])
[1, 2]
>>> min([1,2,3],(1,3,3),key = lambda x:x[1])
[1, 2, 3]
>>> min([1,2,3],(1,3,3),key = lambda x:x[2])
[1, 2, 3]
>>> min([1,4,3],(1,3,3),key = lambda x:x[2])
[1, 4, 3]
>>> min([1,4,3],(1,3,3),key = lambda x:x[0])
[1, 4, 3]
>>> min([1,4,3],(1,3,3),key = lambda x:x[1])
(1, 3, 3)
>>> min([1,4,3],(1,3,3),key = lambda x:x[1])
(1, 3, 3)