方法 1:使用 enumeratelen

通过 enumerate 函数和 len 函数,你可以获取当前迭代的索引,并判断是否是最后一次迭代。

my_list = [1, 2, 3, 4, 5]

for index, item in enumerate(my_list):
    if index == len(my_list) - 1:
        print(f"This is the last iteration: {item}")
    else:
        print(f"Item: {item}")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

方法 2:使用迭代器和 next

将列表转换为迭代器,并在每次循环中使用 next 获取下一个元素。这样你可以提前查看下一个元素,从而判断是否是最后一次迭代。

my_list = [1, 2, 3, 4, 5]
iterator = iter(my_list)
last_item = next(iterator)

for item in iterator:
    print(f"Item: {last_item}")
    last_item = item
print(f"This is the last iteration: {last_item}")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

方法 3:使用 islicechain

通过 itertools.isliceitertools.chain,可以创建一个带有标志的迭代器,标识是否是最后一次迭代。

from itertools import islice, chain

my_list = [1, 2, 3, 4, 5]
iterator = iter(my_list)

# 创建一个带有标志的迭代器,标识是否是最后一次迭代
for current_item, next_item in zip(iterator, chain(islice(iterator, 1, None), [None])):
    if next_item is None:
        print(f"This is the last iteration: {current_item}")
    else:
        print(f"Item: {current_item}")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

方法 4:使用自定义迭代器

定义一个自定义迭代器,该迭代器在最后一次迭代时发出信号。

class LastItemFlagIterator:
    def __init__(self, iterable):
        self.iterator = iter(iterable)
        self.last_item = None
        self.finished = False

    def __iter__(self):
        return self

    def __next__(self):
        if self.finished:
            raise StopIteration
        if self.last_item is not None:
            current_item = self.last_item
        else:
            current_item = next(self.iterator)
        try:
            self.last_item = next(self.iterator)
        except StopIteration:
            self.finished = True
            self.last_item = None
        return current_item, self.finished

my_list = [1, 2, 3, 4, 5]

for item, is_last in LastItemFlagIterator(my_list):
    if is_last:
        print(f"This is the last iteration: {item}")
    else:
        print(f"Item: {item}")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.