我正在尝试为列表中的最后一项执行不同的任务。但我为所有项目执行任务,包括最后一项,然后再次为最后一项执行其他任务。例如,我有一个类似文本和选择按钮的列表。最后我需要文本,选择按钮和后退按钮。这是我的代码:
array = ["string1", "string2", "string3", "string4", "string5"]
for item in array:
theTask()
if array.index(item) == len(array) - 1:
theOtherTask()
我知道自己的错误,但这是我得到的最好的结果。我该如何解决这个问题?
最佳答案
不确定你想做什么,但可能是这样的
for item in array[:-1]:
theTask()
item = array[-1]
theOtherTask()
或者
for index, item in enumerate(array):
if index < len(array) - 1:
theTask()
else:
theOtherTask()
关于python - 为列表的最后一项运行不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455188/