Python——第四章:内置函数(下)

发布时间 2023-11-30 11:52:31作者: Magiclala

内置函数的使用方法:

zip: 可以把多个可迭代内容进行合并
sorted: 排序
filter: 筛选
map:    映射

zip

我们想把每个列表的第1位、第2位、第3位打包放在一起,手写的操作方法如下:

#       0         1       2
lst1 = ["赵本山", "范伟", '苏有朋']
lst2 = [40, 38, 42]
lst3 = ["卖拐", "耳朵大有福", "情深深雨蒙蒙"]

result = []
for i in range(len(lst1)):
    first = lst1[i]
    second = lst2[i]
    third = lst3[i]
    result.append((first, second, third))
print(result)

#运行结果
[('赵本山', 40, '卖拐'), ('范伟', 38, '耳朵大有福'), ('苏有朋', 42, '情深深雨蒙蒙')]

在python中的zip函数可以直接实现这样的操作,下面我们先来看下zip中有哪些功能,

result =zip(lst1,lst2,lst3)
print(dir(result))

#运行结果
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']