在自学习嵌套循环时,我遇到了一个我真正需要帮助的练习。代码从列表中对名称中的元音进行计数,并在外部循环完成后将其放入新列表中。这是我的代码:
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()
输出:
[3, 1, 1, 2, 1, 1, 5]
我的代码不算好...例如,名称Kelsey
中的元音包含2个e
,但它只有1个。我认为range(len(vowels))
可能是问题,但我我不太确定。我尝试研究SO数据库上的类似主题,但找不到我要搜索的内容。请帮我正确编写这段代码。非常感谢你。
PS。使用python 3.5
答案 0 :(得分:5)
你不必在Python上努力。这将是你的Pythonic解决方案
for name in name_list:
print (len([l for l in name if l in "aeiouAEIOU"]))
答案 1 :(得分:1)
if vowels[i] in name:
count += 1
对于任何数量的出现,只需要加1。相反,你可以做
count += name.count(vowels[i])
你也可以像这样迭代字符串的字符:
for vowel in vowels:
# use vowel
还有更多"简化"可能在python的神奇世界中:
def get_list_of_vowel_count(name_list):
vowels = "aeiouAEIOU"
for name in name_list:
yield sum([name.count(vowel) for vowel in vowels])
或采用其解决方案:
def get_list_of_vowel_count(name_list):
vowels = "aeiouAEIOU"
for name in name_list:
yield len([c for c in name if c in vowels])
yield
基本上只是意味着"附加到返回的列表"。它不需要手动填充列表并在以后返回。
如果你因为某些原因想要发疯,你也可以将外部循环放入列表理解中:
def get_list_of_vowel_count(name_list):
return [len([c for c in name if c in "aeiouAEIOU"])
for name in name_list]
答案 2 :(得分:1)
def get_list_of_vowel_count(name_list):
return [[name.count(v) for v in "aeiouAEIOU"] for name in name_list]