将输入字符串的字母与元音列表进行比较,并按字母输出结果

时间:2018-03-06 16:55:46

标签: python python-3.x python-2.7

在以下代码中,用户可以添加任何值。然后我有两个不同的列表。我想找到列表1中的内容或列表2中的答案是真还是假

#enter code here 
n= (input("enter any alphabate: "))
list1= ['a','e','i','o','u'];
list2 = ['A','E','I','O','U'];
for strng in (n):
 if n == list1 or n == list2:
    print("number is  vowel")
 else:
    print("number is not vowel")

1 个答案:

答案 0 :(得分:4)

以下是您的代码的简化版本。

mystr = input("Enter any letters: ")

vowels = set('aeiou')

for idx, i in enumerate(mystr, 1):
    if i.lower() in vowels:
        print('{0}: Letter {1} is a vowel'.format(idx, i))
    else:
        print('{0}: Letter {1} is not a vowel'.format(idx, i))

<强>解释

  • 优良作法是使用set进行比较,因为它会产生O(1)复杂性查找。
  • 您可以使用str.format()将字母包含在字符串中。
  • 转换为小写,因此不需要2组元音。
  • 使用enumerate提取字母数。

这可以进一步缩短:

for idx, i in enumerate(mystr, 1):
    print('{0}: Letter {1} is{2}a vowel'\
          .format(idx, i, ' ' if i.lower() in vowels else ' not '))
相关问题