元音查找器,错误:列表索引超出范围

时间:2015-10-14 02:48:27

标签: python

我是一个完全的初学者。 我正在尝试制作一个可以在输入字符串中找到元音的程序。 请帮助!

    #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

4 个答案:

答案 0 :(得分: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)

注意:它更多&#39; pythonic&#39;为变量提供更具表现力的名称,并尽可能迭代遍历for循环中的元素,而不是索引。

答案 1 :(得分: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']

答案 2 :(得分: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 :(得分:1)

with sets:

st =&#34;美好的一天&#34;

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