python3.x zip用法小结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python3.x zip用法小结

bitcarmanlee   2022-11-16 我要评论

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.迭代器的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

上面的代码,输出结果为

<class 'zip'>
('a', '1')
('b', '2')
('c', '3')
('d', '4')

首先可以看到的是,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)

('a', '1')
('b', '2')
('c', '3')
('d', '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

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

('a', '1')
('b', '2')
('c', '3')
('d', '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)

{'lili': 98, 'lucy': 10, 'tracy': 75, 'larry': 90}

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)

输出的结果为

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

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

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)

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

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}")

profit is: 1200
profit is: 1600
profit is: 2150

当然我们也可以使用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}")

很明显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)

上面代码运行的结果为

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们