2016-12-04 175 views
-3

我有這個數組AR,我需要從它的每個單詞中刪除元音。我如何去做這件事?我已經嘗試過.pop和.remove,但這不起作用。如何從數組中的字符串中刪除字母?

ar=["house","place","oipa"] 

def noWovels(inList): 
    wovels=["a","e","i","o","u","y"] 
    for word in inList: 
     for letter in word: 
      if letter in wovels: 
       inList[word].remove(letter) ? 
       inList.replace(letter,"") ? 
       word.pop(letter) ? 
    return inList 

print(noWovels(ar)) 
+0

重複:http://stackoverflow.com/ q/3559559/1110928 – apnorton

+0

由於這個問題是重複的,請看原始問題。另外,'ar'不是*數組,它是一個列表。 – daniel451

回答

0

列表理解應該是整齊的。

>>> [''.join(j for j in i if j not in 'aeiou') for i in ar] 
['hs', 'plc', 'p'] 
1

您可能使用簡單的列表解析表達爲達到相同的:

>>> vowels = 'aieou' 
>>> word_list = ["house","place","oipa"] 
>>> [''.join(c for c in word if c not in vowels) for word in word_list] 
['hs', 'plc', 'p'] 

,或者可選地使用filter列表解析(未建議)作爲內:

>>> [''.join(filter(lambda c: c not in vowels, word)) for word in word_list] 
['hs', 'plc', 'p'] 

說明:

這些列表理解表情邏輯等同於:

new_list = [] 
for word in word_list: 
    new_word = '' 
    for c in word: 
     if c not in vowels: 
      new_word += c 
    new_list.append(new_word) 
+0

這是如何工作的? – zzz

+0

@zzz:新增說明。 –

+0

謝謝,但我沒有得到你先寫的方式,(c爲單詞c中的c)單詞,爲什麼在()之前加入? – zzz

0

基於您的代碼:

ar = ["house", "place", "oipa"] 

def noWovels(inList): 
    wovels = ["a", "e", "i", "o", "u", "y"] 
    for i, word in enumerate(inList): 
     for w in wovels: 
      word = word.replace(w, "") 
     inList[i] = word 

    return inList 

print(noWovels(ar))