• python3.x zip用法详解


    1.zip用法简介

    在python 3.x系列中,zip方法返回的为一个zip object可迭代对象

    class zip(object):
        """
        zip(*iterables) --> zip object
        
        Return a zip object whose .__next__() method returns a tuple where
        the i-th element comes from the i-th iterable argument.  The .__next__()
        method continues until the shortest iterable in the argument sequence
        is exhausted and then it raises StopIteration.
        """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    通过上面的注释,不难看出该迭代器的两个关键点:
    1.迭代器的next方法返回一个元组,元组的第i个元素为各个输入参数的第i个元素。
    2.迭代器的next方法,遇到输入序列中最短的那个序列迭代完毕,则会停止运行。

    为了看清楚zip的效果,我们先看个最简单的例子

    def fun0():
        a = ['a', 'b', 'c', 'd']
        b = ['1', '2', '3', '4']
        result = zip(a, b)
        print(type(result))
        try:
            while True:
                print(next(result))
        except StopIteration:
            pass
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    上面的代码,输出结果为

    
    ('a', '1')
    ('b', '2')
    ('c', '3')
    ('d', '4')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    首先可以看到的是,zip方法返回的,是一个zip对象。
    zip对象是个迭代器,用next方法即可对其完成遍历。

    当然我们也可以用for循环完成对zip对象的遍历。

    def fun00():
        a = ['a', 'b', 'c', 'd']
        b = ['1', '2', '3', '4']
        result = zip(a, b)
        for ele in result:
            print(ele)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    ('a', '1')
    ('b', '2')
    ('c', '3')
    ('d', '4')
    
    • 1
    • 2
    • 3
    • 4

    2.参数不等长进行截断

    zip方法中,如果传入的参数不等长,则会进行截断,截断的时候会取最短的那个序列,超过最短序列长度的其他序列元素,则会被舍弃掉。

    def fun0():
        a = ['a', 'b', 'c', 'd']
        b = ['1', '2', '3', '4', '5', '6']
        result = zip(a, b)
        try:
            while True:
                print(next(result))
        except StopIteration:
            pass
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    上述的方法如果运行,结果为

    ('a', '1')
    ('b', '2')
    ('c', '3')
    ('d', '4')
    
    • 1
    • 2
    • 3
    • 4

    3.python3.x 与2.x中zip的不同

    python3.x中,zip方法返回的是一个zip对象,本质是一个迭代器。而在python2.x中,zip方法直接返回一个list。
    返回迭代器的好处在于,可以节省list占用的内存,只在有需要的时候再调用相关数据。

    4.用zip方法构建字典

    zip方法在实际中用途非常广泛,我们下面可以看几个实际中常用的例子。
    zip方法可以用来构建字典。
    字典包含两部分数据:key列表与value列表。如果我们现在有key序列与value序列,用zip方法可以很快构建一个字典。

    def fun5():
        names = ['lili', 'lucy', 'tracy', 'larry']
        scores = [98, 10, 75, 90]
        my_dict = dict(zip(names, scores))
        print(my_dict)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    {'lili': 98, 'lucy': 10, 'tracy': 75, 'larry': 90}
    
    • 1

    5.对多个序列的元素进行排序

    排序也是日常工作中的常见需求,对多个序列进行排序而不破坏其元素的相对关系,也非常常见。下面我们来看一个常见的案例

    还是以之前的数据为例
    有names序列与scores序列,我们希望按照names进行排序,同时保持对应的scores数据。

    def fun3():
        names = ['lili', 'lucy', 'tracy', 'larry']
        scores = [98, 10, 75, 90]
        data = sorted(list(zip(names, scores)), key=lambda x: x[0], reverse=False)
        print(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出的结果为

    [('larry', 90), ('lili', 98), ('lucy', 10), ('tracy', 75)]
    
    • 1

    如果我们希望按照分数逆序排,则可以按如下代码运行

    def fun3():
        names = ['lili', 'lucy', 'tracy', 'larry']
        scores = [98, 10, 75, 90]
        data = sorted(list(zip(names, scores)), key=lambda x: x[1], reverse=True)
        print(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    [('lili', 98), ('larry', 90), ('tracy', 75), ('lucy', 10)]
    
    • 1

    6.对多组数据进行计算

    假设我们有3个序列,sales,costs,allowances。其中利润为销售额-成本+补贴,现在我们想求每组利润,就可以使用zip方法。

    def fun4():
        sales = [10000, 9500, 9000]
        costs = [9000, 8000, 7000]
        allowances = [200, 100, 150]
        for sale, cost, allowance in zip(sales, costs, allowances):
            profit = sale - cost + allowance
            print(f"profit is: {profit}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    profit is: 1200
    profit is: 1600
    profit is: 2150
    
    • 1
    • 2
    • 3

    当然我们也可以使用for循环

    def fun4():
        sales = [10000, 9500, 9000]
        costs = [9000, 8000, 7000]
        allowances = [200, 100, 150]
        for sale, cost, allowance in zip(sales, costs, allowances):
            profit = sale - cost + allowance
            print(f"profit is: {profit}")
    
        for i in range(len(sales)):
            profit = sales[i] - costs[i] + allowances[i]
            print(f"profit is: {profit}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    很明显zip方法比for循环还是要更直观,更简洁,更优雅。

    7.*操作符进行解压

    我们还可以使用*操作符对zip对象进行解压,效果是将zip object还原至原来的对象,效果就类似于压缩以后得解压。

    def fun():
        a = ['a', 'b', 'c', 'd']
        b = ['1', '2', '3', '4']
        result = list(zip(a, b))
        print(result)
        zipobj = zip(a, b)
        a1, a2 = zip(*zipobj)
        print(list(a1))
        print(a2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    上面代码运行的结果为

    [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
    ['a', 'b', 'c', 'd']
    ('1', '2', '3', '4')
    
    • 1
    • 2
    • 3
  • 相关阅读:
    SpringMVC入门
    分享画PAD图的软件-PADFlowChart
    JMeter的基本使用
    odoo关于计算字段store=True时导致的安装/更新时间较长问题的解决方案
    openGauss学习笔记-107 openGauss 数据库管理-管理用户及权限-三权分立
    如何判断去噪之后的变压器局部放电是内部还是外部信号
    Gbase8s数据库ALTER PROCEDURE 语句
    分清楚各式各样的USB接口!一帖搞定
    技术分享 | 接口自动化测试如何处理 Header cookie
    基于Python的接口自动化-JSON模块的操作
  • 原文地址:https://blog.csdn.net/bitcarmanlee/article/details/127824164