反转列表中的lambda python函数

时间:2016-09-15 12:26:41

标签: python

scores = []
with open("scores.txt") as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))
        scores.sort(key=lambda s: s[1])
for name, score in scores:
    print(name + ", " + str(score))

此代码可用于显示如下所示的txt文件(无序):

alpha, 3
beta, 1
gamma, 2

看起来像这样:

beta, 1
gamma, 2
alpha, 3

如何修改代码,使其打印为:

alpha, 3
gamma, 2
beta, 1 

3 个答案:

答案 0 :(得分:2)

reverse参数用于True

if (Directory.Exists(path1))
{
    if (File.Exists(path1 + "\\launchinfo.txt"))
    {
        File.Delete(path1 + "\\launchinfo.txt");
        using (FileStream fs = File.Create(path1 + "\\launchinfo.txt"))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("[Connection]\n" + Form1.ipaddress + "\nport=0000\nclient_port=0\n[Details]\n" + Form1.playername);
            fs.Write(info, 0, info.Length);
        }
    }
    else
    {
        using (FileStream fs = File.Create(path1 + "\\launchinfo.txt"))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("[Connection]\n" + Form1.ipaddress + "\nport=0000\nclient_port=0\n[Details]\n" + Form1.playername);
            fs.Write(info, 0, info.Length);
        }
    }
}

来自文档:

  

reverse 是一个布尔值。如果设置为{{1}},则列表元素为   排序好像每个比较都被颠倒了。

答案 1 :(得分:1)

在最后一个for循环中使用scores[::-1]代替scores。以下是此行为的一个小例子:

a=list(range(10))
print(a[::-1])

答案 2 :(得分:0)

排序时使用reverse

>>> l  = [('a', 1), ('c',5), ('a', 2), ('b', 1)]
>>> l.sort(key=lambda i: i[1], reverse=True)
>>> l
[('c', 5), ('a', 2), ('a', 1), ('b', 1)]

您可以将其与sorted

一起使用
>>> l  = [('a', 1), ('c',5), ('a', 2), ('b', 1)]
>>> sorted(l, key=lambda i: i[1], reverse=True)
[('c', 5), ('a', 2), ('a', 1), ('b', 1)]
>>>