2 回答

TA貢獻(xiàn)1757條經(jīng)驗 獲得超7個贊
您可以使用嵌套for循環(huán)遍歷counties列表和每個縣的字符,如果字符在vowels列表中,則以字符為鍵繼續(xù)遞增輸出字典:
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從字符串列表中提取元音字符的生成器表達(dá)式:
from collections import Counter
Counter(c for county in counties for c in county.lower() if c in vowels)

TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊
我相信您正在嘗試執(zhí)行我在下面列出的操作(我省略了您的國家/地區(qū)列表)。我嘗試添加注釋,您可以添加打印行以查看每段代碼在做什么。
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}
添加回答
舉報