我有一個從 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 用于此作業。
uj5u.com熱心網友回復:
假設您有一本字典,其中鍵是國家/地區名稱,值是人口,要通過減少人口來列印有序串列,您可以執行以下操作:
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
?
uj5u.com熱心網友回復:
原來這里的解決方案非常簡單。需要將人口資料從 str 更改為 int。
# Create dictionary of data
data = {}
for i in range(len(countries)):
data[countries[i]] = int(population[i])
這允許正確地對人口進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333888.html
下一篇:檢查總訂單是否細化了部分訂單
