[英]Assigning return value of a function to a variable in Python
我有一個函數可以計算列表中的最大值:
def max_in_list(list):
max = 0
for i in range(len(list)-1):
if list[i] > list [i+1] and list [i] > max:
max = list[i]
elif list[i +1] > max:
max = list [i+1]
print max
另一個將字符串的長度映射到新列表
def maps(list):
list_integer = []
for i in list:
list_integer.append(len(i))
print list_integer
我想用這個計算最長的單詞:
def the_longest_word(list):
new_list = maps(list)
max_in_list(new_list)
看起來第一個函數返回 None。 我的問題是如何將返回值分配給變量以便我可以在第二個函數中使用它?
您需要在函數結束時return
結果而不是打印:
def max_in_list(list):
max = 0
for i in range(len(list)-1):
if list[i] > list [i+1] and list [i] > max:
max = list[i]
elif list[i+1] > max:
max = list [i+1]
return max
和:
def maps(list):
list_integer = []
for i in list:
list_integer.append(len(i))
return list_integer
所以最后一個函數應該是這樣的:
def the_longest_word(list):
new_list = maps(list)
return max_in_list(new_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.