3 回答

TA貢獻(xiàn)1765條經(jīng)驗 獲得超5個贊
這個特定的練習(xí)旨在用雙遞歸來解決,而不是用迭代和單遞歸的組合來解決
我的遞歸方法是保持簡單,讓遞歸為您完成工作:
VOWELS = set("aeiuo???AEIUO???")
def without_vowels(argument):
if not argument:
return argument
head, *tail = argument
if isinstance(head, list):
head = without_vowels(head)
elif head in VOWELS:
return without_vowels(tail)
return [head, *without_vowels(tail)]
用法
>>> test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]
>>> without_vowels(test)
[['h', 'j'], ['t', 's', 'c']]
>>>

TA貢獻(xiàn)1785條經(jīng)驗 獲得超4個贊
我試圖在單個列表理解中實現(xiàn)它,但我太累了,無法讓它工作。
這是我對您的問題的解決方案:
def without_vowels(arg):
vowels = "aeiuo???AEIUO???"
returnList = []
for entry in arg:
if type(entry) == str and entry not in vowels:
returnList.append(entry)
elif type(entry) == list:
returnList.append(without_vowels(entry))
return returnList
test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]
print(without_vowels(test))
以及上面代碼的輸出:
>>> without_vowels(test)
[['h', 'j'], ['t', 's', 'c']]
編輯:我想我的解決方案會返回一個空列表,如果列表中唯一的條目是元音,但如果沒關(guān)系,那么這應(yīng)該可以完成工作。

TA貢獻(xiàn)1875條經(jīng)驗 獲得超3個贊
我認(rèn)為以下實現(xiàn)使您的問題沒有實際意義:
VOWELS = set("aeiuo???AEIUO???")
def without_vowels(arg):
if isinstance(arg, list):
return [without_vowels(item) for item in arg if without_vowels(item)]
elif isinstance(arg, str):
non_vowels = [ch for ch in arg if ch not in VOWELS]
if len(non_vowels) > 2:
return non_vowels
elif len(non_vowels) == 1:
return non_vowels[0]
return non_vowels
test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]
print(without_vowels(test)) # -> [['h', 'j'], ['t', 's', 'c']]
添加回答
舉報