[英]Can I write a lambda function in python of more than one line, and call other functions?
[英]Can I create a master function in Python to take a single line of other functions?
我有兩個函數,其中大多數包含相同的代碼。 如果傳入的數組包含所有正數,則一個返回“ True”,而如果數組包含所有可被10整除的數字,則一個返回“ True”。
我想將這兩個函數組合成這樣的函數:
def master_function(array, function):
for i in array:
if function:
result = True
else:
result = False
break
print(result)
return result
唯一會變化的部分是If語句中的“函數”。 當我用缺少的行編寫函數時,在程序執行時不會調用它們。
def positive_integers(array):
i >= 0
def divisible_by_10(array):
i%10 == 0
測試代碼也不執行。
master_function([10,20,30,35],divisible_by_10)
您的函數沒有返回任何東西,您需要讓它們訪問i
:
def positive_integers(i):
return i >= 0
def divisible_by_10(i):
return not i%10
def master_function(array, function):
for i in array:
if function(i):
result = True
else:
result = False
break
print(result)
return result
def master_function(array, function):
for i in array:
print str(i)
if function(i):
result = True
else:
result = False
print(result)
return result
def positive_integers(i):
if i >= 0:
return True
def divisible_by_10(i):
if i%10 == 0:
return True
master_function([10,20,30,35],divisible_by_10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.