Python输出排序

2024-09-29 22:31:33 发布

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

我有我的代码设置,所以它得到一个API,并输出到一个.txt文件中的某些变量,但我希望它自己的顺序,而不是按字母顺序或任何东西,但在优先级顺序,所以如果其中一个变量是MVP,它将被放置在较高的.txt作为VIP和80将高于20 这是一个.txt的示例

b-88698@alt.com : thegiant20** [10]
e-b77b2@alt.com : Rancher** [1] [VIP]
5-c1eb6@alt.com : dogdad** [4] [VIP]
1-15a1f@alt.com : mb1mi** [0]
5-cd91b@alt.com : shalexa** [18] [MVP_PLUS]

但我要订的是这样的

5-cd91b@alt.com : shalexa** [18] [MVP_PLUS]
5-c1eb6@alt.com : dogdad** [4] [VIP]
e-b77b2@alt.com : Rancher** [1] [VIP]
b-88698@alt.com : thegiant20** [10]
1-15a1f@alt.com : mb1mi** [0]

有没有什么我可以投入,可以轻松实现这一点


Tags: txtcom顺序plusrancheraltvipmvp
1条回答
网友
1楼 · 发布于 2024-09-29 22:31:33

listsort方法有一个key参数,您可以在其中提供一个函数来确定排序顺序。此函数必须找到它是MVP还是VIP,并且必须找到方括号中的值

import re

def main():
    lines = [
        'b-88698@alt.com : thegiant20** [10]',
        'e-b77b2@alt.com : Rancher** [1] [VIP]',
        '5-c1eb6@alt.com : dogdad** [4] [VIP]',
        '1-15a1f@alt.com : mb1mi** [0]',
        '5-cd91b@alt.com : shalexa** [18] [MVP_PLUS]',
    ]

def sortkey(value):
    is_mvp = '[MVP' in value
    is_vip = '[VIP' in value
    group = re.search(r'\[(\d+)\]', value)
    number = int(group[1])
    return is_mvp, is_vip, number

    lines.sort(key=sortkey, reverse=True)
    for line in lines:
        print(line)


if __name__ == '__main__':
    main()

比较是用一个元组来完成的。第一个值表示我们是否有MVP。相应的值为TrueFalse(或视为整数10)。第二个值与VIP相同。最后一个值是括号中转换为整数的数字

结果

5-cd91b@alt.com : shalexa** [18] [MVP_PLUS]
5-c1eb6@alt.com : dogdad** [4] [VIP]
e-b77b2@alt.com : Rancher** [1] [VIP]
b-88698@alt.com : thegiant20** [10]
1-15a1f@alt.com : mb1mi** [0]

return之前的sortkey函数中添加以下行,您将看到为其生成并用于排序的值和键

    print(f'{value} -> key ({int(is_mvp)}, {int(is_vip)}, {number})')

输出

b-88698@alt.com : thegiant20** [10] -> key (0, 0, 10)
e-b77b2@alt.com : Rancher** [1] [VIP] -> key (0, 1, 1)
5-c1eb6@alt.com : dogdad** [4] [VIP] -> key (0, 1, 4)
1-15a1f@alt.com : mb1mi** [0] -> key (0, 0, 0)
5-cd91b@alt.com : shalexa** [18] [MVP_PLUS] -> key (1, 0, 18)

相关问题 更多 >

    热门问题