[英]Define multiple functions in loop
我是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)
.
.
.
按照您的建議定義功能被認為是不好的做法。 最好的方法是在外部定義函數,並在需要使用它們的地方調用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.