簡體   English   中英

從嵌套列表中刪除所有元音,python

[英]Removing all vowels from nested lists, python

我想從輸入列表中刪除所有元音,我已經走到了這一步

def without_vowels(seq):
vowels = ["a", "e", "i", "o", "u", "y", "w"]
listx = []
for i in seq:
    if isinstance(i, list):
        return without_vowels(seq[0]) + without_vowels(seq[1:])
    elif not i in vowels:
        listx.append(i)
return listx

但是當我將以下列表放入我的 function

test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]

我明白了

['h', 'j', 't', 's', 'c']

這是部分正確的,但我應該得到以下 output,

[['h', 'j'], ['t', 's', 'c']]

問題在於

return without_vowels(seq[0]) + without_vowels(seq[1:])

您不想return找到的第一個列表,我不確定您為什么總是在同一個索引處切片。

當您到達子列表時,您只是想更深入地了解一個級別,因此您需要將上面的行更改為:

listx.append(without_vowels(i))

你的邏輯有缺陷。 在您的 if 語句中,您返回的結果沒有存儲在任何地方,這就是您沒有得到所需結果的原因。

你可以試試這段代碼,對於這種情況,集合操作更容易理解和實現:

test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]
vowels = {"a", "e", "i", "o", "u", "y", "w"}
result = []
for item in test:
    matches = set(item) - vowels
    if matches:
        result.append(list(matches))
print(result)

這將產生[['j', 'h'], ['t', 'c', 's']]作為最終的 output。 如果你理解這里的邏輯,你也可以使用函數式編程。


vowels = set(["a", "e", "i", "o", "u", "y", "w"])

#spicing it up a bit to make sure it handles deep nesting
# test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]
test = ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o",["a","b","c",["a","e"]]]]


def without_vowels(seq, vowels):
    "pass in vowels to avoid global lookups"
    out = []
    for v in seq:
        if isinstance(v,list):
            novowels = without_vowels(v, vowels)
            if novowels:
                out.append(novowels)
        else:
            if not v in vowels:
                out.append(v)
    return out

print(without_vowels(test,vowels))

output:

[['h', 'j'], ['t', 's', 'c', ['b', 'c']]]

並給出原始test

[['h', 'j'], ['t', 's', 'c']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM