简体   繁体   中英

Python 2.7: Determining the length when using next with a python Iterator

I am performing the following extraction and it is working:

>>> lines = ["cat 23\n", "dog 11\n"]
>>> "".join(lines).split()
['cat', '23', 'dog', '11']
>>> data = iter("".join(lines).split())
>>> [(next(data), next(data)) for i in range(2)]
[('cat', '23'), ('dog', '11')]

However if I change lines to be equals to:

lines = ["cat 23\n"]

I get a StopIteration with no list produced.

EDIT: As with the responses below, the answer was because I was using 2 instead of 1. is there a way to get the length of an iterator without consuming it?

That list comprehension is basically:

l = list()
l.append((next(data), next(data)))
l.append((next(data), next(data)))

You are calling next(data) four times on an iterator that evidently gives only two elements.

You specified two pairs when iterating when it should be one to reflect your list of lines:

size = len("".join(lines).split()) # size of list
[(next(data), next(data)) for i in range(size / 2)]

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