我只是遇到了这个问题,我的通用解决方案使用迭代器:
from typing import TypeVar, Iterable
E = TypeVar('E')
def metait(i: Iterable[E]) -> Iterable[tuple[E, bool, bool]]:
first = True
previous = None
for elem in i:
if previous:
yield previous, first, False
first = False
previous = elem
if previous:
yield previous, first, True
您将收到一个元组,其中包含第一项和最后一项的原始元素和标志。它可以用于每个可迭代对象:
d = {'a': (1,2,3), 'b': (4,5,6), 'c': (7,8,9)}
for (k,v), is_first, is_last in metait(d.items()):
print(f'{k}: {v} {is_first} {is_last}')
这将给你:
a: (1, 2, 3) True False
b: (4, 5, 6) False False
c: (7, 8, 9) False True