python - 为列表的最后一项运行不同的函数

标签 python list python-3.x loops

我正在尝试为列表中的最后一项执行不同的任务。但我为所有项目执行任务,包括最后一项,然后再次为最后一项执行其他任务。例如,我有一个类似文本和选择按钮的列表。最后我需要文本,选择按钮和后退按钮。这是我的代码:

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/

相关文章:

python argparse - 如何允许解析器处理标志和非标志参数

Python 计算字典中值的出现次数

python - 如何从文件中读取数字并将其作为 float 存储在列表中?/Python

python - 2 组并集不包含所有项目

python - 停止内部迭代并找到 2 个元组的范围

python - 循环依赖导致 ImportError : cannot import name

python - imread 返回 None,违反函数 'cvtColor' 错误中的断言 !_src.empty()

c# - Enumerable.Empty<T>() 等同于 IList?

python - 正则表达式 Python 问题

regex - 从文本文件中提取信息 block 并创建 Pandas 数据框并存储