[英]How does a list of function work in Python?
I saw a code (these functions are from sklearn module imports)我看到了一段代码(这些函数来自sklearn模块导入)
classifiers = [
LinearDiscriminantAnalysis(),
GaussianNB(),
KNeighborsClassifier(3),
SVC(kernel="linear", C=0.25),
SVC(gamma=2, C=1),
DecisionTreeClassifier(max_depth=2),
AdaBoostClassifier(),
]
I was trying to understand what the above code does, so I tried playing with a small test我试图理解上面的代码是做什么的,所以我尝试玩一个小测试
But, when I do this,但是,当我这样做时,
def function0():
print("0")
def function1():
print("1")
lst = [function0(), function1()]
for i in range(2):
print(lst[i])
it prints,它打印,
0
1
None
None
I believe I understood the code wrong... Could anyone help me understand what I'm missing?我相信我理解错了代码......谁能帮助我理解我错过了什么?
--------------------------------- edit ------------------------------- - - - - - - - - - - - - - - - - - 编辑 - - - - - - - - ---------------
def function0():
return 0
def function1():
return 1
lst = [function0(), function1()]
for i in range(2):
print(lst[i])
I figured out what I did wrong.我想通了我做错了什么。
The problem is that you functions return nothing (which is assumed to be None
when called).问题是您的函数不返回任何内容(在调用时假定为
None
)。
You can try this instead:你可以试试这个:
def function0():
print("0")
def function1():
print("1")
lst = [function0, function1]
for func in lst:
func()
I have modified the code so it will be easy to understand.我已经修改了代码,所以它很容易理解。
The 2 functions are called and print what they print.调用这两个函数并打印它们打印的内容。
Each function return None
so the list is populated with 2 None values每个函数都返回
None
因此列表中填充了 2 个 None 值
def function0():
print("0")
return None
def function1():
print("1")
return None
lst = [function0(), function1()]
print('-------------------')
for i in range(2):
print(lst[i])
output输出
0
1
-------------------
None
None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.