第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python - 遍歷列表以計算元音并將數(shù)字放入字典中

Python - 遍歷列表以計算元音并將數(shù)字放入字典中

慕勒3428872 2021-11-23 19:27:38
我需要編寫一個程序,其中有一個縣名列表,我需要找到該列表中的 5 個元音中的每個元音的數(shù)量,并將這 5 個數(shù)字放入字典中。我想做一個 for 循環(huán)來遍歷每個元音,每次遍歷循環(huán)時,在字典中添加一個新條目,以元音為鍵,以計數(shù)為值。它應(yīng)該打?。簕'a':4, 'e':4, 'i':4, 'o':4, 'u':4}。我不知道有多少元音,所以我只為示例中的所有值寫了 4??h的列表真的很長,所以我只是在這里粘貼了一個縮短的版本。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 非常陌生,不知道自己在做什么。我不能讓它工作,絕對不能在字典中得到它。任何幫助,將不勝感激!
查看完整描述

2 回答

?
長風(fēng)秋雁

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)


查看完整回答
反對 回復(fù) 2021-11-23
?
慕的地8271018

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}


查看完整回答
反對 回復(fù) 2021-11-23
  • 2 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號