简体   繁体   中英

How do I loop through functions with a for loop?

If I have different functions with increasing numbers in their names how do I loop through them? For example:

def Func1():
    something something

def Func2():
    something something

def Func3():
    something something

can I loop through them with a:

for i in range(1,4):

You can put the functions in a list and loop over that:

for func in [Func1, Func2, Func3]:
    result = func()

Functions are first-class objects in Python, you can create (additional) references to them and call them from whatever reference you have.

You could do:

for fn in [Func1, Func2, Func3]:
    fn(arg1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM