在自学习嵌套循环时,我遇到了一个我真正需要帮助的练习.代码从列表中对名称中的元音进行计数,并在外部循环完成后将其放入新列表中.这是我的代码:
def get_list_of_vowel_count(name_list):
vowels = "aeiouAEIOU"
count_list = []
count = 0
for name in name_list:
for i in range(len(vowels)):
if vowels[i] in name:
count += 1
count_list += [count]
count = 0
return count_list
def main():
name_list = ["Mirabelle", "John","Kelsey","David","Cindy","Dick","aeeariiiosoisduuus"]
vowel_counts = get_list_of_vowel_count(name_list)
print(vowel_counts)
main()
Run Code Online (Sandbox Code Playgroud)
输出:
[3, 1, 1, 2, 1, 1, 5]
我的代码不太好...例如,名称Kelsey中的元音包含2 e但它只有1个.我认为range(len(vowels))可能是问题但我不太确定.我尝试研究SO数据库上的类似主题但却找不到我在寻找什么.请帮我正确编写这段代码.非常感谢你.
PS.使用python 3.5
你不必在Python上努力.这将是您的Pythonic解决方案
for name in name_list:
print (len([l for l in name if l in "aeiouAEIOU"]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |