Python 3 中的 zip() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31683959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:24:56  来源:igfitidea点击:

The zip() function in Python 3

python

提问by dhaliman

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

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

I define two lists:

我定义了两个列表:

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

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

我通过zip()以下方式使用这些:

1. test1 = zip( lis1, lis2)

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

when I type test1at the interpreter, I get this:

当我test1在口译员处打字时,我得到以下信息:

"zip object at 0x1007a06c8"

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.

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

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

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

采纳答案by Brien

Unlike in Python 2, the zipfunction 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

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

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

回答by Anand S Kumar

The zip()function in Python 3 returns an iterator. That is the reason why when you print test1you get - <zip object at 0x1007a06c8>. From documentation-

zip()Python 3 中的函数返回一个迭代器。这就是为什么打印时test1会得到 -的原因<zip object at 0x1007a06c8>从文档-

Make an iterator that aggregates elements from each of the iterables.

制作一个迭代器,聚合来自每个可迭代对象的元素。

But once you do - list(test1)- you have exhausted the iterator. So after that anytime you do list(test1)would only result in empty list.

但是一旦你这样做了——list(test1)你已经用尽了迭代器。因此,在此之后,您所做的任何时候list(test1)都只会导致空列表。

In case of test2, you have already created the list once, test2is a list, and hence it will always be that list.

在 的情况下test2,您已经创建了一次列表,test2是一个列表,因此它将始终是该列表。