python - 为什么我的字典排序功能不能正常工作?
问题描述
我有一个从 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
</p>
推荐阅读
- google-translate - 如何使用 Google 音译 API 使用 Key
- python - 使用pandas模块创建excel文件时如何保持整列中两个变量之间的公共空间
- python - askdirectory() 关闭 Tkinter 窗口
- php - 严格比较失败 laravel Blade,我犯了一些愚蠢的错误
- arrays - 如何在没有结果的情况下将 sha256 的前 128 位作为 u128?
- sap-cloud-sdk - SuccessFactors 实体上的 SAP Java Cloud SDK 计数查询不起作用
- go - 对同一存储库中的多个包使用公共库
- angularjs - 我们如何在 AngularJS 中不使用幻数验证 SVG 图像
- tabulator - 制表符 - 查找列表排序
- reactjs - 如果卡片快速刷卡,则 useEffect 进入无限循环