【问题标题】:List Being Ordered Alphabetically Instead of Numerically列表按字母顺序而不是数字顺序排列
【发布时间】:2020-01-28 22:05:23
【问题描述】:

我已经积累了一个分数列表,其中包含在列表中获得特定分数的人的用户名。

然后我使用以下代码按降序排列分数。

winnerScore.sort()
winnerScore.reverse()

以下是列表'winnerScore'打印时的结果。

['j 78', 'j 36', 'i 90', 'i 58']

函数根据用户名对它们进行排序,而不是根据实际代码。

负责列表排序的函数如下:

global winnerScore
with open("diceRoll.txt","r") as x_file:
    contents = x_file.readlines()

oneScore = contents[count-1]
oneScore = oneScore.split(" ")
print(oneScore)
n = oneScore[-2][-1] + " " + oneScore[-1]

winnerScore.append(n)

if len(oneScore) != 0:
    winnerScore.sort()
    winnerScore.reverse()

我已经从一个文本文件中读取了分数和用户名。

我可以进行哪些更改以确保列表“winnerScore”是根据用户名的实际分数排序的?

【问题讨论】:

    标签: python arrays list


    【解决方案1】:

    默认情况下,字符串的排序顺序是按字母顺序排列的。

    要自定义排序,您可以添加key-function

    这是一个成功的例子:

    >>> def extract_number(score):
            "Convert the string 'j 78' to the number 78"
            level, value = score.split()
            return int(value)
    
    >>> scores = ['j 78', 'j 36', 'i 90', 'i 58']
    >>> scores.sort(key=extract_number)
    >>> scores
    ['j 36', 'i 58', 'j 78', 'i 90']
    

    希望这会有所帮助:-)

    【讨论】:

      【解决方案2】:

      要按数字排序,您需要提取数字并将其视为int,将其用作排序键。像这样:

      winnerScore = sorted(winnerScore, reverse=True, key=lambda x: int(x.split()[1]))
      

      上面的表达式会得到你期望的值:

      winnerScore
      => ['i 90', 'j 78', 'i 58', 'j 36']
      

      【讨论】:

      • 我在其中添加了这些结果:['h 52', 'z 52', 'z 82', 'h 68']
      • 对我来说结果是['z 82', 'h 68', 'h 52', 'z 52']。我希望你没有忘记再次分配变量;)检查我更新的答案。
      • 我一发表评论,就意识到了错误。但现在可以了 :) 感谢您的帮助!
      • @M.IbtihazIslam 太棒了!请不要忘记接受最佳答案;)
      【解决方案3】:

      您可以尝试类似的方法,根据分数对输入的元素进行排序

      x.sort(key= lambda i:i.split(' ')[-1], reverse=True)
      

      其中 x 是包含输入的列表,名称和分数由空格 (' ') 分隔

      希望对xx有帮助

      【讨论】:

        【解决方案4】:

        您可以在自定义 sort 函数中使用正则表达式,如果您的字符串中有超过 1 个空格,这可能会有所帮助:

        import re
        scores = ['j 78', 'j 36', 'i 90', 'i 58']
        
        def get_score(username_score):
            score = re.search(r'\d+', username_score).group()
            return int(score)
        
        scores.sort(key=get_score) 
        

        输出:

        ['j 36', 'i 58', 'j 78', 'i 90']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-07
          • 1970-01-01
          • 2020-03-29
          • 2018-09-15
          • 2012-02-17
          • 1970-01-01
          • 2018-03-10
          相关资源
          最近更新 更多