python - 在循环中定义多个函数
问题描述
我是 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)
.
.
.
解决方案
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.
推荐阅读
- python - python中的SQL查询哈希值
- image - 如何将使用图像提供程序从图库中选择的捕获或图像保存到资产文件夹中?
- python - 使用请求在 Python 中不使用 Javascript 进行网页抓取
- php - 表单提交后Laravel显示空值
- swift - 使用 GeometryReader 绘制形状
- python - 最小化力的最佳轨迹,最终条件问题
- javascript - 在 Firebase 云函数中批量处理 Promise
- java - 出于某种原因,共享首选项默认为 true
- scala - 如何在 Intellij 的 Scala 中运行 Main 方法
- c# - 如何从另一个程序集将 DBContext 添加到服务