环境
pycharm2013
python 中有多种方法可以判断当前循环是否是最后一次
方法
- 使用
enumerate()
enumerate()函数可以直接获取当前的元素的索引,如果循环对象是个可迭代的对象,例如列表,元组等,获取最后一个元素,
items = ['apple', 'banana', 'cherry']
for index, item in enumerate(items):
if index == len(items) - 1:
print(f"This is the last item: {item}")
else:
print(item)
2.如果对象是个列表,可以使用切片方式
切片中有现成的获取最后一个对象的方式,例如list[-1]
items = ['apple', 'banana', 'cherry']
for item in items:
if item == items[-1]:
print(f"This is the last item: {item}")
else:
print(item)
3.使用iter()
和 next()
对于更复杂的情况,可以使用迭代器和next()
函数配合一个异常处理来判断最后一次迭代。但是这种方法通常用于更高级的迭代逻辑,对于简单的情况并不推荐
items = ['apple', 'banana', 'cherry']
iterator = iter(items)
try:
while True:
current_item = next(iterator)
next_item = next(iterator, None)
if next_item is None:
print(f"This is the last item: {current_item}")
break
else:
print(current_item)
except StopIteration:
pass