gpt4 book ai didi

python - 是否有一种 pythonic 方式知道何时传递 for 中的第一个和最后一个循环?

转载 作者:太空狗 更新时间:2023-10-29 21:32:33 26 4
gpt4 key购买 nike

我有一个模板,我在其中放置了 5 个表单,但除了第一个表单外,所有表单都无法发布。仅当我首先单击启用它的按钮时,才能填写下一个表单。

我正在寻找一种在验收测试中的 for 循环中实现类似 Django 的 forloop.last templatetag 变量的方法,以决定是否执行启用下一个表单的方法。

基本上我需要做的是:

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

最佳答案

我不知道有什么内置的,但你可以轻松地编写一个生成器来为你提供所需的信息:

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!

关于python - 是否有一种 pythonic 方式知道何时传递 for 中的第一个和最后一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7365372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com