這里的任務是:
A. match_ends 給定一個字串串列,回傳字串長度為 2 或更多且字串的第一個和最后一個字符相同的字串數量的計數。注意:python 沒有 運算子,但 = 有效。
def match_ends(words):
for i in words:
if (len(i) >= 2) & (i[0] == i[-1]):
return [i]
print(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']))
輸出是:
['阿巴']
uj5u.com熱心網友回復:
問題是回傳第一個并且它不會繼續
return 關鍵字停止函式,所以你必須將它存盤在一個類似陣列的陣列中才能回傳它
這是優化的代碼:
def match_ends(*words):
result = []
for i in list(words):
if len(i) >= 2 and i[0] == i[-1]:
result.append([i])
return result
print(match_ends('aba', 'xyz', 'aa', 'x', 'bbb'))
uj5u.com熱心網友回復:
if (len(i) >= 2) & (i[0] == i[-1]):
return [i]
當您的 if 條件為真時回傳,這將停止您的功能。
如果您想將資料的所有出現都res.append(i)保存為(將 i 保存在串列 res 中),您應該將資料保存在一個變數中
當您遍歷所有串列時,然后將其回傳到外面。
def match_ends(words):
for i in words:
if (len(i) >= 2) & (i[0] == i[-1]):
res.append(i)
return res
uj5u.com熱心網友回復:
發生這種情況是因為您的第一個專案與您的 if 條件相匹配,并且當您使用 return 時,您的代碼以結果作為第一專案退出。我不確定你想用這個函式做什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398290.html
