首页 > 解决方案 > 在循环中定义多个函数

问题描述

我是 python 新手,需要编写一个循环,为列表中的每个元素声明一个函数。这些函数将在循环之后使用。循环中的最后一个元素需要额外处理。

假设我有这个列表

elements = ['element_1' ,'element_2', 'element_3']

我试过了:

for i, item in enumerate(elements) : 

    if (i+1) == len(elements):
        def action(focus = 'action_' + str(i)) :
            print ("action_" + str(i) + " : " + item)
            .
            .
            .
    else :
        def action(focus = 'action_' + str(i)) :
            print ("action_" + str(i) + " : " + item)
            .
            .
            .

标签: pythonloops

解决方案


It is considered bad practice to have functions defined as you are suggesting. The best way to do it is to have function defined at the outer level, and call them wherever you need to use them.


推荐阅读