python list(zipobject)返回空的(列表)容器 [英] python list(zipobject) returns empty (list) container

查看:62
本文介绍了python list(zipobject)返回空的(列表)容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 3.4.3中遇到了一个奇怪的问题,似乎在任何地方都没有提及.

I have run into a strange issue in Python 3.4.3, and it doesn't seem to be mentioned anywhere.

让我们说:
a = [1,2,3,4] b = [5,6,7,8]

要在垂直方向上串联它们: ab = zip(a,b)在 python 3 中,ab 本身会返回:

To concatenate these vertically: ab = zip(a,b) in python 3, ab itself would return:

zip对象(以十六进制数字表示)

zip object at (some hexnumber)

这里很好,在python 3中,检索了连接列表:
aabb =列表(ab)

All well here, in python 3, to retrieve the concatenated list:
aabb = list(ab)

现在这是一个问题,第一次, aabb 确实会返回真实列表:
[(1,5),(2,6),(3,7),(4,8)]

Now heres the issue, first time, aabb will indeed return a real list:
[(1, 5), (2, 6), (3, 7), (4, 8)]

第二次及以后,如果再次执行整个过程,则 list(aabb)只会返回一个空的 [] 容器,就像 list()可以.

Second time and onwards however, if you do the whole process again list(aabb) will simply return an empty [] container, just like list() would do.

只有重新启动shell/解释器后,它才能再次工作.

It will only work again after I restart shell/interpreter.

这是正常现象还是错误?

Is this normal or a bug?

编辑:好的,我没有意识到这与 zip 有关,它的SEEMED常量为 ab 返回相同的十六进制值每次,所以我认为这与 list(ab)有关.

EDIT: Ok guys I didn't realise it was to do with zip, it SEEMED constant as ab returned the same hex value everytime so I thought it was to do with list(ab).

无论如何,可以通过重新分配 ab = zip(ab)

Anyway, worked out by reassigning ab = zip(ab)

根据我在答案和原始链接中所了解的, ab 一经阅读就会被处理掉.

From what I understand in answers and original link, ab gets disposed once read.

推荐答案

此问题不是由 list(aabb)引起的,而是由您的 list(ab)引起的现在的代码:

This problem will not be created by list(aabb) but with list(ab) in your code right now:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

ab = zip(a, b)
aabb = list(ab)

print(list(ab))  # -> []

问题是 zip 迭代器一次存储值,然后按如下方式处理:

The problem is that zip is an iterator which stores values once and are then disposed like so:

ab = zip(a, b)  # iterator created
aabb = list(ab)  # elements read from ab, disposed, placed in a list

print(list(ab))  # now ab has nothing because it was exhausted

另一方面,这应该起作用,因为 aabb 只是一个列表,而不是穷尽的迭代器 ab :

This on the other hand should work because aabb is just a list, not the exhausted iterator ab:

ab = zip(a, b)
aabb = list(ab)

print(list(aabb))  # -> [(1, 5), (2, 6), (3, 7), (4, 8)]

这篇关于python list(zipobject)返回空的(列表)容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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