我正在學(xué)習(xí) Python 并試圖解決同樣的問題(“朋友還是敵人?”)。我編寫了下面的代碼,并想了解如何按照“我的邏輯”方式繼續(xù)前進(jìn)。看起來它只將第一個(gè)項(xiàng)目添加到列表中new_friends,但不會(huì)迭代列表的所有元素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循環(huán)..但沒有成功將其他項(xiàng)目添加到列表中new_friends。
1 回答

倚天杖
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是您的函數(shù)的修復(fù)版本,我相信您想要的功能:
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]
對于該函數(shù)的任一版本,如下:
print(friend(["Ryan", "Kieran", "Jason", "Yous"]))
結(jié)果是這樣的:
['Ryan', 'Yous']
添加回答
舉報(bào)
0/150
提交
取消