简体   繁体   English

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

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

I have an assignment to import a data set from a csv, and the final portion of the assignment has me stuck, specifically:我有一个从 csv 导入数据集的任务,任务的最后一部分让我卡住了,特别是:

The countries are listed in order from most populous (China) to least (Holy See)这些国家按人口最多(中国)到最少(教廷)的顺序列出

The issue comes from the fact that the resulting list orders itself alphabetically (by country) or seemingly at random.问题来自这样一个事实,即结果列表按字母顺序(按国家/地区)或看似随机排序。

    # 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")

I've tried changing key=lambda x: x[1] to key=lambda x: x[0] but this orders the list by country as opposed to the population count.我已经尝试将key=lambda x: x[1]更改为key=lambda x: x[0]但这会按国家/地区而不是人口计数对列表进行排序。

EDIT:编辑:

The csv for the assignment comes from here: https://think.cs.vt.edu/corgis/csv/covid/作业的 csv 来自这里: https : //think.cs.vt.edu/corgis/csv/covid/

The current output looks like this but needs to look like this当前输出看起来像这样但需要看起来像这样

Further, I cannot use pd for this assignment.此外,我不能将 pd 用于此作业。

Assuming you have a dictionary where the key is the country name and the value is it's population, to print out an ordered list by decreasing population you can do the following:假设您有一本字典,其中键是国家/地区名称,值是人口,要通过减少人口来打印有序列表,您可以执行以下操作:

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]}')

This produces the following output:这会产生以下输出:

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

Turns out the solution here is very simple.原来这里的解决方案非常简单。 The population data needs to be changed from a str to an int.需要将人口数据从 str 更改为 int。

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

This allows for the population to properly be sorted.这允许正确地对人口进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM