zip函数: zip函数用于在将可迭代对象作为参数,将对象对应的元素打包成一个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度和最短的对象相同吗,利用*操作符,可以将列表解压为列表。 a = [1,2,3] b = [4,5,6] c = [4,5,6,7,8] zipped = zip(a,b) # 打包为元组的列表 输出结果:[(1, 4), (2, 5), (3, 6)] zip(a,c) # 元素个数与最短的列表一致 输出结果:[(1, 4), (2, 5), (3, 6)] zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式 输出结果:[(1, 2, 3), (4, 5, 6)]
dict函数: dict函数时 用来生成一个字典。
dict 语法: class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)
参数说明: **kwargs -- 关键字 mapping -- 元素的容器。 iterable -- 可迭代对象。
返回值 返回一个字典。
实例
以下实例展示了 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}