2 回答
TA贡献1757条经验 获得超7个赞
您可以使用嵌套for循环遍历counties列表和每个县的字符,如果字符在vowels列表中,则以字符为键继续递增输出字典:
d = {}
for county in counties:
for character in county.lower():
if character in vowels:
d[character] = d.get(character, 0) + 1
d 变成:
{'a': 16, 'u': 10, 'i': 4, 'o': 14, 'e': 14}
或者,您可以使用collections.Counter从字符串列表中提取元音字符的生成器表达式:
from collections import Counter
Counter(c for county in counties for c in county.lower() if c in vowels)
TA贡献1796条经验 获得超4个赞
我相信您正在尝试执行我在下面列出的操作(我省略了您的国家/地区列表)。我尝试添加注释,您可以添加打印行以查看每段代码在做什么。
vowels = ('a', 'e', 'i','o', 'u')
d={}
## select countries 1 at a time
for country in countries:
# convert each country to lowercase, to match list of vowels, otherwise, you need to deal with upper and lowercase
country = country.lower()
# select letter in country 1 at a time
for i in range(len(country)):
# check to see whether the letter selected in the country, the ith letter, is a vowel
if (country[i] == 'a') or (country[i] == 'e') or (country[i] == 'i') or (country[i] == 'o') or (country[i] == 'u'):
# if the ith letter is a vowel, but is not yet in the dictionary, add it
if (country[i]) not in d:
d[country[i]] = 1
# if the ith letter is a vowel, and is already in the dictionary, then increase the counter by 1
else:
d[country[i]] += 1
print(d) # {'a': 16, 'u': 10, 'i': 4, 'o': 14, 'e': 14}
添加回答
举报