2015-10-14 64 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