使用python显示单词列表中的元音

2024-04-26 11:51:34 发布

您现在位置:Python中文网/ 问答频道 /正文

wordlist = ['dog', 'cat', 'mouse', 'alpaca', 'penguin', 'snail']

我怎么能像上面那样拿一张单子让python

  1. 检查列表中的每3个元素,并计算该字符串中的元音数
  2. 打印字符串及其包含的元音数
  3. 如果字符串包含3个或更多元音,则退出循环

Tags: 字符串元素列表catpenguin单子元音dog
1条回答
网友
1楼 · 发布于 2024-04-26 11:51:34

要从worldlist中获取每3个元素,请使用:

wordlist[0::3]

这意味着,从索引0开始,然后遍历将索引递增3的列表。你知道吗

现在,要得到元音的数量,你有很多选择:

  • 使用列表理解,可以:

     vowels = 'aeiouy'
     vowels_only = [c for c in w.lower() if c in 'aeiou']
    
  • 使用regex并替换:

     import re
     re.sub(r'[aeiou]', '', w, flags=re.IGNORECASE)
    

总而言之,你会得到:

wordlist = ['dog', 'cat', 'mouse', 'alpaca', 'penguin', 'snail']

for w in wordlist[0::3]:      
  vowels_only = [c for c in w.lower() if c in 'aeiou']
  nb_vowels = len(vowels_only) 
  print("%s (%d)" % (w, nb_vowels)) # print the word and vowels count
  if nb_vowels >= 3:
    break

相关问题 更多 >