3 回答
TA贡献1765条经验 获得超5个赞
这个特定的练习旨在用双递归来解决,而不是用迭代和单递归的组合来解决
我的递归方法是保持简单,让递归为您完成工作:
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贡献1785条经验 获得超4个赞
我试图在单个列表理解中实现它,但我太累了,无法让它工作。
这是我对您的问题的解决方案:
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']]
编辑:我想我的解决方案会返回一个空列表,如果列表中唯一的条目是元音,但如果没关系,那么这应该可以完成工作。
TA贡献1875条经验 获得超3个赞
我认为以下实现使您的问题没有实际意义:
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']]
添加回答
举报