【问题标题】:Why won't my dictionary sorting function work properly?为什么我的字典排序功能不能正常工作?
【发布时间】:2021-12-09 03:26:07
【问题描述】:

我有一个从 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/

当前输出looks like this但需要look like this

此外,我不能将 pd 用于此作业。

【问题讨论】:

  • 欢迎来到Stack Overflow.!如果不查看数据以及您编写的产生问题的代码,很难回答您的问题。请编辑您的问题并显示countriespopulation 变量中的数据样本。
  • 如果您的数据来自 CSV,请使用 pandas 排序并输出到新文件。不是字典
  • 您的人口值仍然是字符串,并且按字母顺序排列,而不是与数值有任何关系。

标签: python csv sorting


【解决方案1】:

原来这里的解决方案非常简单。人口数据需要从 str 更改为 int。

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

这样可以对总体进行正确排序。

【讨论】:

    【解决方案2】:

    假设您有一个字典,其中键是国家名称,值是人口,要通过减少人口打印出有序列表,您可以执行以下操作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2020-07-16
      • 1970-01-01
      • 2021-02-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多