对列表中带有整数的字符串进行排序

Sort strings accompanied by integers in list

我正在尝试制作排行榜。 这是我的清单:

list=['rami4\n', 'kev13\n', 'demian6\n']

我希望能够将此列表从最高数字排序到最小数字,或者甚至从最小数字到最高数字,给出如下内容:

list=['kev13\n', 'demian6\n', 'rami4\n']

我尝试使用 re.findall('\d+', list[loop])[0] 之类的东西,但我只设法从列表中获得最佳播放器。不想为尽可能多的玩家重复代码,有人有想法吗?

你确实必须使用re module, but also the key parameter of the sort()方法。

reg = re.compile('\w*?(\d+)\n')
lst.sort(key=lambda s: int(reg.match(s).group(1)))

使用 findall() 效果很好,就像你一样:

reg = re.compile('\d+')
lst.sort(key=lambda s: int(reg.findall(s)[0]))

请注意,我 compile() 正则表达式,因此它是一劳永逸地计算的,而不是针对列表中的每个元素。

我有一个基于面向对象编程和覆盖 str__lt__ 特殊方法的其他解决方案。

import re

class SpecialString(str):
    def __lt__(self, other):
        pattern=re.compile(r"\d+")
        return int(pattern.search(str(self)).group(0)) <  int(pattern.search(str(other)).group(0))

if __name__ == "__main__":
    listing = ['rami4\n', 'kev13\n', 'demian6\n']
    spe_list = [SpecialString(x) for x in listing]
    spe_list.sort()
    print(spe_list)

哪个打印到标准输出:

['rami4\n', 'demian6\n', 'kev13\n']

此方法允许您不重写sort函数并使用内置函数(可能已优化)。此外,由于您的字符串可能被认为是 "specialization of the str class",因此继承机制非常适合,因为您保留其所有属性但重写其比较机制。