有没有更具Python风格的方法来判断for循环的第一次和最后一次迭代?

7 投票
7 回答
570 浏览
提问于 2025-04-17 01:55

我有一个模板,里面放了5个表单,但除了第一个表单外,其他的都不能提交。只有点击一个按钮,才能让下一个表单变得可填写。

我想在一个接受测试的循环中实现类似Django中的forloop.last这个变量,以决定是否执行一个方法来启用下一个表单。

基本上,我需要做的事情是这样的:

for form_data in step.hashes:
    # get and fill the current form with data in form_data
    if not forloop.last:
        # click the button that enables the next form
# submit all filled forms

7 个回答

2

你可以使用 enumerate 这个功能,然后把计数器和列表的长度进行比较:

for i, form_data in enumerate(step.hashes):
    if i < len(step.hashes):
        whatever()
4

我不知道有没有现成的功能,但你可以很简单地写一个生成器来获取你需要的信息:

def firstlast(seq):
    seq = iter(seq)
    el = prev = next(seq)
    is_first = True
    for el in seq:
        yield prev, is_first, False
        is_first = False
        prev = el
    yield el, is_first, True


>>> list(firstlast(range(4)))
[(0, True, False), (1, False, False), (2, False, False), (3, False, True)]
>>> list(firstlast(range(0)))
[]
>>> list(firstlast(range(1)))
[(0, True, True)]
>>> list(firstlast(range(2)))
[(0, True, False), (1, False, True)]
>>> for count, is_first, is_last in firstlast(range(3)):
    print(count, "first!" if is_first else "", "last!" if is_last else "")


0 first! 
1  
2  last!
0

如果我理解你的问题没错的话,你是想要一个简单的方法来判断你是在列表的开头还是结尾,对吧?

如果是这样的话,下面的代码可以帮你实现:

for item in list:
    if item != list[-1]:
        #Do stuff

对于列表中的第一个项目,你需要把“-1”换成0。

撰写回答