按字母顺序而不是数字顺序排列的列表

2024-07-04 07:53:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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”是基于用户名的实际分数排序的


Tags: 函数代码功能列表排序contentssortglobal
3条回答

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

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

上述表达式将产生您期望的值:

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

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

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

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

希望对xx有帮助

默认情况下,字符串的排序顺序为字母顺序

要自定义排序,可以添加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']

希望这有帮助:-)

相关问题 更多 >

    热门问题