2024-09-27 21:28:55 发布
网友
我找不到任何(对初学者来说)可读的信息。是否可以在for循环中的最后一项上发生事件:
array = ["foo", "bar", "john", "test"] for item in array: print item LastItemEvent: forLoop + lastItem def lastItem: # call another function doneWithLoop()
或者我需要一个递增的整数计数等等?很糟糕的例子,但我希望你们能理解。
item将作为循环结束时的最后一个元素,因为它接受数组中的每个值(list really),因此一旦完成,它将被设置为最后一个元素。在
item
array = ["foo", "bar", "john", "test"] for item in array: print item print "last item", item
我想你可以用else语句:
for x in range(10): print x else: print x**2
来自Python文档:
When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.
我猜你在做一些奇怪的事情,如果你解释一下你真正想做什么,会有更好的解决办法。但是如果你真的想做你所要求的,你可以只迭代所有元素,但最后一个元素除外:
for item in array[:-1]: do_something(item)
在那之后,你当然可以用最后一个元素做一些其他的事情:
item
将作为循环结束时的最后一个元素,因为它接受数组中的每个值(list really),因此一旦完成,它将被设置为最后一个元素。在我想你可以用else语句:
来自Python文档:
我猜你在做一些奇怪的事情,如果你解释一下你真正想做什么,会有更好的解决办法。但是如果你真的想做你所要求的,你可以只迭代所有元素,但最后一个元素除外:
在那之后,你当然可以用最后一个元素做一些其他的事情:
^{pr2}$相关问题 更多 >
编程相关推荐