直接上代码
def func1():print("func1")def func2():print("func2")def func3():print("func3")def func4():print("func4")func_list = [func1, func2, func3, func4]for func in func_list:func()
结果如下
func1
func2
func3
func4
如果在项目中,假设要让用户做出选择,这么写容易扩展
def first():print("first option")def second():print("second option")def third():print("third option")options = {"1": first,"2": second,"3": third
}print("1. first 2. second 3. third")
choice = input("选择:")
func = options.get(choice)
if func:func()
else:print("无这选项")
结果如下:
1. first 2. second 3. third
选择:4
无这选项
1. first 2. second 3. third
选择:1
first option
其实还可以将上面的代码进行修改
def first():print("first option")def second():print("second option")def third():print("third option")options = {"1": [first, "first"],"2": [second, "second"],"3": [third, "third"]
}optionList = []
for k,v in options.items():option = "{}.{}".format(k, v[-1])optionList.append(option)
choices = " ".join(optionList)
print(choices)choice = input("选择:")
func = options.get(choice)
if func:func[0]()
else:print("无这选项")
结果如下
1.first 2.second 3.third
选择:5
无这选项
点个赞呗~