我需要编写一个程序,在其中列出县名列表,并且需要找到该列表中5个元音中的每个元音中的多少个,并将5个数字放入字典中。
我想做一个for循环来遍历每个元音,并且每次遍历循环时,都在字典中添加一个新条目,其中元音作为键,而count作为值。
它应该打印:{'a':4, 'e':4, 'i':4, 'o':4, 'u':4}
。我不知道有多少个元音,所以我只为示例中的所有值写了4个。
县列表真的很长,所以我在这里粘贴了一个简短的版本。
counties = ['Autauga','Baldwin','Barbour','Bibb','Blount','Bullock','Butler','Calhoun','Chambers','Cherokee','Chilton','Choctaw','Clarke','Clay','Cleburne','Coffee','Colbert','Conecuh','Coosa','Covington','Crenshaw','Cullman','Dale','Dallas']
letter = ('a', 'e', 'i', 'o', 'u')
counter = 0
d={}
for it in clist:
def func(clist, letterlist, count):
count += clist.count(letterlist)
print("the number of vowels:" count)
return count
func(counties, letter, counter)
如您所见,我是Python的新手,也不知道我在做什么。我无法使其正常工作,而且绝对无法在字典中获得它。
任何帮助将不胜感激!
答案 0 :(得分:1)
您可以使用嵌套的for
循环遍历counties
列表和每个县的字符,并且如果字符位于{{ 1}}列表:
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
答案 1 :(得分:0)
我相信您正在尝试做下面的事情(我省略了您所在的国家/地区列表)。我尝试添加注释,然后可以添加打印行以查看每段代码的作用。
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}