【问题标题】:Reading both numbers in an integer instead of the first when sorting排序时以整数而不是第一个数字读取两个数字
【发布时间】:2014-12-03 15:54:01
【问题描述】:

我正在尝试对文本文件中的数据进行排序并在 python 中显示。

到目前为止我有:

                text_file = open ("Class1.txt", "r")
                data = text_file.read().splitlines()

                namelist, scorelist = [],[]
                for li in data:
                    namelist.append(li.split(":")[0])
                    scorelist.append(li.split(":")[1])
                scorelist.sort()
                print (scorelist)
                text_file.close()

它对数据进行排序,但是它只读取第一个数字:

['0', '0', '10', '3', '3', '5']

10 读作“1”

这是我的文本文件的样子:

Harry:3
Jarrod:10
Jacob:0
Harold:5
Charlie:3
Jj:0

【问题讨论】:

    标签: python sorting integer


    【解决方案1】:

    是字典排序,如果需要整数排序,追加拆分为int

    scorelist.append(int(li.split(":")[1]))
    

    【讨论】:

      【解决方案2】:

      由于scorelist字符串 的列表,"10" 出现在"3" 之前,因为"10" 中的第一个字符小于"3" 中的第一个字符(字典排序——就像字典中的单词)。这里的诀窍是告诉 python 对整数进行排序。正如其他答案所指出的那样,您可以通过对整数列表而不是字符串列表进行排序来做到这一点,您可以使用key 函数进行排序:

      scorelist.sort(key=int)
      

      这告诉python将项目排序为整数而不是字符串。这里的好处是您根本不需要更改数据。你仍然会得到一个字符串列表而不是整数列表——你只需告诉 python 更改它比较字符串的方式。整洁。


      演示:

      >>> scorelist = ['3', '10', '0', '5', '3', '0']
      >>> scorelist_int = [int(s) for s in scorelist]
      >>>
      >>> scorelist.sort(key=int)
      >>> scorelist
      ['0', '0', '3', '3', '5', '10']
      >>>
      >>> scorelist_int.sort()
      >>> scorelist_int
      [0, 0, 3, 3, 5, 10]
      

      【讨论】:

        【解决方案3】:

        数据实际上是字符串。排序就像在字典中一样。

        您应该将分数转换为 int:

        scorelist.append(int(li.split(":")[1]))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-25
          • 1970-01-01
          • 2023-03-16
          相关资源
          最近更新 更多