如何判断Python中zip()函数生成的对象是否为空?
zip() Generated Object is Empty (Including Your Specific Example) Great question! Since zip() in Python 3 returns an iterator (not a list or other sequence), you can’t directly use len() to check if it’s empty—iterators don’t store their full length in memory. Here are reliable, practical methods to determine if a zip object is empty, along with how to apply them to your code:
Method 1: Efficient Check with next() (Preserves the Iterator)
This approach only checks the first element of the iterator, making it memory-efficient even for large datasets. If you need to use the iterator after checking, we can "restore" the first element we pulled out.
import itertools # Your original data transactions = ['001','002','003'] transaction_dates = ['01-01-2019','01-02-2019','01-03-2019'] transaction_amounts = ['27.00','35.00','36.00'] results = zip(transactions, transaction_dates, transaction_amounts) is_empty = False try: # Try to get the first element of the zip iterator first_item = next(results) # Restore the iterator by chaining the first element back in results = itertools.chain([first_item], results) except StopIteration: # If StopIteration is raised, the iterator is empty is_empty = True print(f"Is results empty? {is_empty}") # Output: Is results empty? False
Method 2: Simple Check by Converting to a List (Consumes the Iterator)
If you don’t need to reuse the original zip iterator, converting it to a list is the easiest way. Just check if the resulting list is empty:
results = zip(transactions, transaction_dates, transaction_amounts) results_list = list(results) if not results_list: print("Zip object is empty") else: print(f"Zip object has {len(results_list)} items") # Use results_list for further processing (original iterator is now exhausted)
Note: This works well for small datasets, but for very large iterables, converting to a list will use more memory.
Method 3: Reusable Helper Function
For repeated use, wrap the check in a helper function that returns both the empty status and the restored iterator (if not empty):
import itertools def is_iterator_empty(iterator): try: first_element = next(iterator) return False, itertools.chain([first_element], iterator) except StopIteration: return True, iterator # Usage with your data results = zip(transactions, transaction_dates, transaction_amounts) empty_status, results = is_iterator_empty(results) print(f"Empty? {empty_status}")
Key Notes
zip()returns an empty iterator if any of the input iterables is empty (since it stops at the shortest input).- In Python 2,
zip()returns a list instead of an iterator, solen(zip(...))would work directly—but this is irrelevant for modern Python versions.
内容的提问来源于stack exchange,提问作者Reez0

