Python 3 中的 zip() 函数 [英] The zip() function in Python 3

查看:42
本文介绍了Python 3 中的 zip() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 Python 3 中使用 zip() 函数.我的问题是关于以下我觉得很奇怪的问题:

I know how to use the zip() function in Python 3. My question is regarding the following which I somehow feel quite peculiar:

我定义了两个列表:

lis1 = [0, 1, 2, 3]
lis2 = [4, 5, 6, 7]

我通过以下方式在这些文件上使用 zip():

and I use the zip() on these in the following ways:

1. test1 = zip( lis1, lis2)

2. test2 = list(zip(lis1, lis2))

当我在解释器中输入 test1 时,我得到这个:

when I type test1 at the interpreter, I get this:

"zip object at 0x1007a06c8"

所以,我在解释器中输入 list(test1) 并得到预期的结果,但是当我再次输入 list(test1) 时,我得到一个空列表.

So, I type list(test1) at the interpreter and I get the intended result, but when I type list(test1) again, I get an empty list.

我觉得奇怪的是,无论我在解释器中输入多少次 test2 我总是得到预期的结果而不是空列表.

What I find peculiar is that no matter how many times I type test2 at the interpreter I always get the intended result and never an empty list.

推荐答案

与 Python 2 不同,Python 3 中的 zip 函数返回一个 迭代器.迭代器只能被耗尽一次(比如用它们制作一个列表).这样做的目的是通过仅在需要时生成迭代器的元素来节省内存,而不是一次将它们全部放入内存中.如果您想重用您的压缩对象,只需像在第二个示例中一样从中创建一个列表,然后通过类似的内容复制该列表

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

这篇关于Python 3 中的 zip() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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