python3 zip结果使用了两次 [英] python3 zip result used twice

查看:71
本文介绍了python3 zip结果使用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 3的两个不同的 for 循环中的两个列表上使用的 zip 结果是其两倍.

I am using twice the result of zip on two lists in two distinct for loops in Python 3. What's the most pythonic way of writing this ?

  1. 两次使用zip()

  1. Using zip() twice

for j in range(123) :
    for x,y in zip(list1,list2) :
        doSomething()
....
for x,y in zip(list1,list2) :
    doSomethingElse()

  • 将zip结果存储为列表

  • Storing the result of zip as a list

    z=list(zip(list1,list2))
    for j in range(123) :
        for x,y in z :
            doSomething()
    for x,y in z :
        doSomethingElse()
    

  • 在这两种情况下,我都非常想了解Python的内部知识.

    I would really appreciate to hear about the internals of Python in both cases.

    推荐答案

    我将使用第一种方法:

    for j in range(123) :
        for x,y in zip(list1,list2) :
            doSomething()
    ....
    for x,y in zip(list1,list2) :
        doSomethingElse()
    

    在Python 3中,zip方法不会从现有列表中创建新的配对对列表.它只是创建一个迭代器,该迭代器引用每次迭代的输入列表.与创建全新列表的Python 2方法相比,它非常有效.

    In Python 3, the zip method does not create a new list of pairs from your existing lists. It simply creates an iterator that references the input lists for each iteration. It's very efficient compared to the Python 2 way which created an entirely new list.

    由于这个原因,您可以多次使用 zip 命令,因为我相信这使得代码更易于阅读和简洁(在代码顶部,没有实例化新列表引用,在通常,如果可以避免创建命名引用,则要避免创建命名引用,因为它为您提供了另一个您需要记住的引用名称-这也是匿名函数更具吸引力的部分原因.

    For this reason you can use zip command multiple times, as I believe this makes the code easier to read and more succinct (no instantiation of a new list reference at the top of the code, in general you want to avoid create named references if you can avoid it since it gives you one more reference name you need to remember - this is also part of the reason anonymous functions are more appealing).

    这篇关于python3 zip结果使用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆