简体   繁体   English

通过索引获取 itertools 对象,类似于你在列表中的获取方式

[英]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 ?是否有任何快速方法可以轻松地从itertools.izip object导出索引,类似于从list导出的方式?

I am trying to compare 2 values, one from a list, the other from the itertools object.我正在尝试比较 2 个值,一个来自列表,另一个来自 itertools 对象。 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.虽然我可以在对象上使用enumerate来获取值,但似乎我需要在这样做之前迭代所述对象中的所有值。

# 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.您可以使用itertools.islice()对迭代器进行切片,但这当然不是索引操作并且会消耗迭代器。

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

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