簡體   English   中英

為什么我的字典排序功能不能正常工作?

[英]Why won't my dictionary sorting function work properly?

我有一個從 csv 導入數據集的任務,任務的最后一部分讓我卡住了,特別是:

這些國家按人口最多(中國)到最少(教廷)的順序列出

問題來自這樣一個事實,即結果列表按字母順序(按國家/地區)或看似隨機排序。

    # Create dictionary of data
    data = {}
    for i in range(len(countries)):
        data[countries[i]] = population[i]

    # Sort the dictionary by population size
    sorted_data = sorted(data.items(), key=lambda x: x[1], reverse=True)

    # Save and print the formated data
    for i in range(len(sorted_data)):
        outfile.write("{} ".format(i+1) + f'{sorted_data[i][0]:{50}} {sorted_data[i][1]:{50}}' + "\n")
        print("{} ".format(i+1) + f'{sorted_data[i][0]:{50}} {sorted_data[i][1]:{50}}' + "\n")

我已經嘗試將key=lambda x: x[1]更改為key=lambda x: x[0]但這會按國家/地區而不是人口計數對列表進行排序。

編輯:

作業的 csv 來自這里: https : //think.cs.vt.edu/corgis/csv/covid/

當前輸出看起來像這樣但需要看起來像這樣

此外,我不能將 pd 用於此作業。

假設您有一本字典,其中鍵是國家/地區名稱,值是人口,要通過減少人口來打印有序列表,您可以執行以下操作:

cd = {'A':12, 'B': 8, 'C':45, 'D': 4}  # Sample Dictionary
sd = sorted(cd, key= lambda x: cd[x], reverse=True) # Sorted List of Keys
for k in sd:
    print(f'Country: {k} has population {cd[k]}')

這會產生以下輸出:

Country: C has population 45
Country: A has population 12
Country: B has population 8
Country: D has population 4

原來這里的解決方案非常簡單。 需要將人口數據從 str 更改為 int。

    # Create dictionary of data
    data = {}
    for i in range(len(countries)):
        data[countries[i]] = int(population[i])

這允許正確地對人口進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM