简体   繁体   中英

Get itertools object by index, similar to how you get in list

Are there any quick ways that I can easily derive the index from an itertools.izip object , similar to how you derive from a list ?

I am trying to compare 2 values, one from a list, the other from the itertools object. While I can use enumerate on the object to grab the value, it seems that I will need to iterate all the values within the said object before doing so.

# if iterating from a list
list_values = [(1, 'a', 'john'), (2, 'b', 'jack'), (3, 'c', 'jill')]
print list_values[1] # returns me (2, 'b', 'jack')

# if trying to do the same as above but towards an itertools objext
iter_values = itertools.izip([1, 2, 3], ['a', 'b', 'c'], ['john', 'jack', 'jill'])
print iter_values[1] # Errors-out

No you can't index an iterator. That's the trade-off, you don't have to keep the object in memory, but you don't get random access and indexing. You can slice an iterator with itertools.islice() but it's not an indexing operation of course and consumes the iterator.

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