简体   繁体   English

列出有效和非空的zip对象会打印空列表

[英]Listing a valid and non-empty zip object prints empty list

zip_obj is a zip object containing 17292 tuples. zip_obj是一个包含17292个元组的zip对象。 A weird thing is happening with it: 一件奇怪的事情正在发生:

sorted_zip_obj = sorted(zip_obj, key=lambda x: -abs(x[1]))
print(f'{len(list(zip_obj))} {len(sorted_zip_obj)}')

prints 0 17292 . 打印0 17292 How come this happens? 怎么会这样呢? Why the first number printed is 0 and not 17292? 为什么打印的第一个数字是0而不是17292?

zip_obj is something that I am retrieving from somewhere else and unfortunately cannot share, and I cannot reproduce this behavior in small zip objects that I manually create. zip_obj是我从其他地方获取的东西,不幸的是无法共享,并且无法在我手动创建的小型zip对象中重现此行为。

If you're on python 3, zip_obj is probably a lazy zip object which you can iterate over only once. 如果您使用的是python 3,则zip_obj可能是一个懒惰的zip对象,您只能对其进行一次迭代。 You've already exhausted it when you sorted it. 对它进行排序时,您已经筋疲力尽了。

Try realizing it into a data structure like this: 尝试将其实现为这样的数据结构:

zip_obj = tuple(zip_obj) # you can use `list` if you prefer
sorted_zip_obj = sorted(zip_obj, key=lambda x: -abs(x[1]))
print(f'{len(zip_obj)} {len(sorted_zip_obj)}') # removed the redundant `list`

before using it. 在使用它之前。

From the docs for zip : zip文档中:

Make an iterator that aggregates elements from each of the iterables. 创建一个迭代器,以聚合每个可迭代对象中的元素。 Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. 返回一个元组的迭代器,其中第i个元组包含每个参数序列或可迭代对象中的第i个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM