我正在學習 Python 并試圖解決同樣的問題(“朋友還是敵人?”)。我編寫了下面的代碼,并想了解如何按照“我的邏輯”方式繼續前進??雌饋硭粚⒌谝粋€項目添加到列表中new_friends,但不會迭代列表的所有元素x。除了上面之外,返回值是None......我在這里沒有注意到什么?def friend(x): x = ["Ryan", "Kieran", "Jason", "Yous"] new_friends = [] for str in x: if len(str) == 4: return new_friends.append(str) return new_friends[0:]除了if聲明之外,我還嘗試了嵌套while循環..但沒有成功將其他項目添加到列表中new_friends。
1 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
這是您的函數的修復版本,我相信您想要的功能:
def friend(x):
new_friends = []
for str in x:
if len(str) == 4:
new_friends.append(str) # no 'return' here
return new_friends # return resulting list. no need to return a slice of it
這是使用列表理解的更簡潔的版本:
def friend(candidates):
return [candidate for candidate in candidates if len(candidate) == 4]
對于該函數的任一版本,如下:
print(friend(["Ryan", "Kieran", "Jason", "Yous"]))
結果是這樣的:
['Ryan', 'Yous']
添加回答
舉報
0/150
提交
取消