我有一组3个函数以及一个名字列表。我试图循环这些名称并为每个名称调用一个函数。我的python看起来像这样......
def testfunc1():
print("This is a test function 1")
#print(name)
def testfunc2():
print("This is a test function 2")
#print(name)
def testfunc3():
print("This is a test function 3")
#print(name)
name_list = ["John", "Joe", "Paul" "George", "Mark", "Craig", "Norman"]
fn_list = [testfunc1(), testfunc2(), testfunc3() ]
for i, name in enumerate(name_list):
[i % len(fn_list)]()
print(name)
我希望这发生......
John - Run testfunc1
Joe - Run testfunc2
Paul - Run testfunc3
George - Run testfunc1
Mark - Run testfunc2
Craig - Run testfunc3
Norman - Run testfunc1
我的当前代码有几个问题,第一个是目前我收到以下错误...
TypeError: 'list' object is not callable
任何人都可以帮我解决?
答案 0 :(得分:2)
[i % len(fn_list)]()
你实际上做的是“用括号([number]()
)包围的”号码“,你需要先添加列表引用名称。
name_list = ["John", "Joe", "Paul" "George", "Mark", "Craig", "Norman"]
# You need to store the functions' references, not their return values
fn_list = [testfunc1, testfunc2, testfunc3] # remove the parentheses
for i, name in enumerate(name_list):
(fn_list[i % len(fn_list)])() # fn_list[ ... ]
print(name)
输出:
This is a test function 1
John
This is a test function 2
Joe
This is a test function 3
PaulGeorge
This is a test function 1
Mark
This is a test function 2
Craig
This is a test function 3
Norman