简体   繁体   中英

Listing a valid and non-empty zip object prints empty list

zip_obj is a zip object containing 17292 tuples. 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 . How come this happens? Why the first number printed is 0 and not 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.

If you're on python 3, zip_obj is probably a lazy zip object which you can iterate over only once. 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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