2015-10-14 32 views
3

我是一個完整的初學者。 我想做一個程序,可以在輸入字符串中找到元音。 請幫忙!元音查找器,錯誤:列表索引超出範圍

#python 3.4.3 

    z = ['a','e','i','o','u'] 

    n = input('Input string') 

    a = list(n) 

    m = [] 

    for i in range(len(a)): 
     for j in range(len(a)): 
      if z[i] == a[j]: # try to match letter by letter 
       print('vowel found') 
       m.append(z[i]) 
      else: 
       continue 
    print(m) 

和輸出:

Error: 
line 12, in <module> 
    if z[i] == a[j]: 
IndexError: list index out of range 
+2

'範圍(LEN(a))的'應該是'範圍(LEN(Z))' – karthikr

回答

2

的代碼可以修改如下:

for i in z: 
    for j in a: 
     if i == j: # try to match letter by letter 
      print('vowel found') 
      m.append(i) 
     else: 
      continue 
3

這裏有一個更快的一個:

z = ['a','e','i','o','u'] 

n = input('Input string: ') 

m = [x for x in n if x in z] 

print(m) 

沒有必要的雙循環,一旦得到它們就會花費太長時間成更大的名單。

>>> Input string: hello 
>>> ['e', 'o'] 
+0

好建議,然而因爲OP是一個完整的初學者,列表理解可能不是最直觀的把握。所以[這裏是教我列表理解的資源](http://howchoo.com/g/ngi2zddjzdf/how-to-use-list-comprehension-in-python) –

4

你可以嘗試這樣的事情:

vowels = 'aeiou' 
string = input('Input string > ') 
vow_in_str = [] 

for char in string: 
    if char in vowels: 
     vow_in_str.append(char) 

print(vow_in_str) 

注:它更「Python化」給你的變量更具有表現力的名字,以及通過元素在迭代的循環,而不是索引,只要有可能。

+0

另外op指出Python 3.4,raw_input不存在Python 3.x,你應該使用輸入。 –

1

與集:

ST = 「好天氣」

z = ['a','e','i','o','u'] 
# convert st to list of chars 
y = [ch.lower() for ch in st if ch != ' '] 

# convert both list to sets and find the lenght of intersection 
print(len(set(z) & set(y))) 

3