Skip to content

Instantly share code, notes, and snippets.

@lhsfcboy
Last active January 16, 2018 12:14
Show Gist options
  • Save lhsfcboy/308d9c076a614c82841c9a3a869b40ff to your computer and use it in GitHub Desktop.
Save lhsfcboy/308d9c076a614c82841c9a3a869b40ff to your computer and use it in GitHub Desktop.
for循环中判断当前元素是否是最后一个元素
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
# Get an iterator and pull the first value.
it = iter(iterable)
last = next(it)
# Run the iterator to exhaustion (starting from the second value).
for val in it:
# Report the *previous* value (more to come).
yield last, True
last = val
# Report the last value.
yield last, False
for i, has_more in lookahead(range(3)):
print(i, has_more)
# 0 True
# 1 True
# 2 False
# 添加一个序号, 方便拿到index
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
count = 0
# Get an iterator and pull the first value.
it = iter(iterable)
last = next(it)
# Run the iterator to exhaustion (starting from the second value).
for val in it:
# Report the *previous* value (more to come).
count +=1
yield count,last, True
last = val
# Report the last value.
count +=1
yield count,last, False
for i, line, has_more in lookahead(range(3)):
print(i, line, has_more)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment