[英]Different Output in Print and Return in Python Function
我想從第一個字母以 s 開頭的列表中返回單詞,並且我執行了以下 2 個解決方案。 一個接近解決方案,另一個是正確的,但不是所需的確切形式。 如果我在 python function 中使用“打印”與“返回”,我也會得到不同的結果。 為什么呢? 請指導我。
第一種方法:
def s(opt):
for a in opt:
if a[0] == 's':
return(a)
s(['soup','dog','salad','cat','great'])
Output 我通過運行這段代碼得到的是“湯”——也用引號括起來——為什么?
def s(opt):
for a in opt:
if a[0] == 's':
print(a)
s(['soup','dog','salad','cat','great'])
Output 我用這種方法得到的是湯,垂直形式的沙拉,沒有引號等等。 為什么?
我的問題是如何通過在 function 方法中保留返回來獲得所需的 output ? 另一個問題為什么 output 在上述方法中使用 print 和 return 時會有所不同?
所需的 Output:['湯','沙拉']
使用yield
而不是return
。 當您的條件if a[0] == 's'
為真時, s()
function 返回。
如果您想在滿足您的要求時返回多個值,那么您必須使用另一個列表來存儲您的答案,或者您可以使用列表推導
def s(opt):
for a in opt:
if a[0] == 's':
yield a
print(list(s(['soup', 'dog', 'salad', 'cat', 'great'])))
# Output
# ['soup', 'salad']
您使用print
的版本有效,因為它僅在找到值時打印它們,並且在循環結束之前不會從 function 返回。 它不太有用,因為它返回None
,所以你不能利用結果本身——你只能看到打印的 output。
您的return
語句將返回匹配該條件的第一個元素。 在此之后,它不會繼續檢查列表中的其他元素。 您需要構建一個返回值list
:
def s(opt):
result = []
for a in opt:
if a[0] == 's':
result.append(a)
return result
print(s(['soup', 'dog', 'salad', 'cat', 'great']))
此代碼使用list.append
將元素一一添加到result
列表中。 然后,在 function 的末尾,它返回result
。
或者,使用列表推導:
def s(opt):
return [a for a in opt if a[0] == 's']
print(s(['soup', 'dog', 'salad', 'cat', 'great']))
在這兩種情況下,output 都符合要求:
['soup', 'salad']
這是因為一旦您返回 function 中的值,function 就會停止。 一旦它返回湯,整個函數就會停止,但是當你打印出每一個時,你會得到所有的結果。 這是您的問題的解決方案:
def s(opt):
answers = []
for a in opt:
if a[0] == 's':
answers.append(a)
return(answers)
s(['soup','dog','salad','cat','great'])
def s(opt):
matches = []
for a in opt:
if a[0] == 's':
matches.append(a)
return matches
s(['soup','dog','salad','cat','great'])
這應該給你想要的 output
def s(opt):
for a in opt:
if a[0] == 's':
return(a)
# r is soup
r = s(['soup','dog','salad','cat','great'])
def s(opt):
for a in opt:
if a[0] == 's':
print(a)
s(['soup','dog','salad','cat','great'])
# z is None
z = s(['soup','dog','salad','cat','great'])
我建議你使用列表包含你想要的值並返回
def s(opt):
l = []
for a in opt:
if a[0] == 's':
l.append(a)
return l
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.