在 zip 对象列表上执行 len 会清除 zip [英] Performing len on list of a zip object clears zip

查看:30
本文介绍了在 zip 对象列表上执行 len 会清除 zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 zip() 函数时看到了一个奇怪的行为.当我执行以下操作 len(list(z)) 其中 z 是一个 zip 对象时,结果为 0(这对我来说似乎是错误的),并且该操作似乎清除了 zip 对象.有人可以帮助我了解发生了什么.

I am seeing a strange behavior when working with the zip() function. When I perform the following operation len(list(z)) where z is a zip object, the result is 0 (which seems wrong to me), and the action seems to clear out the zip object. Can someone please help me understand what is going on.

# python3
Python 3.2.3 (default, Sep 30 2012, 16:41:36) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> w = [11, 22, 33, 44, 55, 66]
>>> x = [1, 2, 3, 4]
>>> y = ['a', 'b', 'c']
>>> z = zip(x, y, w)
>>> z
<zip object at 0x7f854f613cb0>
>>> list(z)
[(1, 'a', 11), (2, 'b', 22), (3, 'c', 33)]
>>> len(list(z))
0
>>> list(z)
[]
>>> z
<zip object at 0x7f854f613cb0>
>>> 

谢谢,艾哈迈德.

推荐答案

在 Python 3 zip 是一个生成器.当您执行 list(z) 时,生成器正在耗尽.您可以根据生成器返回的值创建一个列表并对其进行操作.

In Python 3 zip is a generator. The generator is being exhausted when you do list(z). You can create a list from the values returned by the generator and operate on that.

l = list(z)
len(l)
# -> 3
l
# -> [(1, 'a', 11), (2, 'b', 22), (3, 'c', 33)]

<小时>

生成器是个好东西.它们允许我们以几乎与编写处理列表的代码相同的方式编写内存高效的代码.使用来自链接维基的示例:


Generators are a good thing. They allow us to write memory-efficient code in nearly the same way we would write code that deals with lists. To use an example from the linked wiki:

def double(L):
    return [x*2 for x in L]

可以重写为生成器以避免在内存中创建另一个列表:

Could be rewritten as a generator to avoid creating another list in memory:

def double(L):
    for x in L:
        yield x*2

这篇关于在 zip 对象列表上执行 len 会清除 zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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