search

Home  >  Q&A  >  body text

语法 - Python如何给sorted里的key动态的传参数

def sort():
    return sorted(a,key=lambda x:(x['name'],x['age']),reverse=True)

就是说如果我传name就按name排序,如果传name和age就按照这两个key双重排序,如果传了三个key以此类推

大家讲道理大家讲道理2900 days ago534

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:54:23

    def sort(*arg):
        return sorted(a,key=lambda x,*arg:(x[y] for y in arg),reverse=True)

    According to your modification, it has not been tested, you can test it. Hope I wrote it correctly.
    This is the result of my test:

    >>> a = {'a': {'a1': 1, 'a2': 2, 'a3': 3}, 'b': {'a1': 2, 'a2': 1, 'a3': 3}, 'c': {'a1': 1, 'a2': 1, 'a3': 3}}
    >>> sort('a1','a2')
    ['c', 'b', 'a']

    It looks like there’s nothing wrong with it

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:54:23

    I don’t know if you want this,
    As follows, the first column in each tuple is the name, the second column is the grade, and the third column is the age
    The purpose is to sort by grade first, and then by age

    # coding: utf-8
    from operator import itemgetter, attrgetter
    
    # 每个tuple中第一列是姓名,第二列是成绩,第三列是年龄
    student = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10)]
    
    # 按照年龄排序
    print(sorted(student, key=itemgetter(2)))
    # 先按照成绩排序,然后按照年龄排序
    print(sorted(student, key=itemgetter(1, 2)))
    

    Refer to the content in the Python cookbook
    Sort a dictionary list by a certain keyword
    You can dynamically pass parameters as follows

    rows = [
        {'fname': 'Brian', 'lname': 'Jones', 'uid': 1010},
        {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
        {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
        {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
    ]
    
    
    def my_sort(*args):
        print(sorted(rows, key=itemgetter(*args)))
        return sorted(rows, key=itemgetter(*args))
        
    hello = my_sort('lname', 'uid')
    print('==' * 40)
    print(hello)
    

    operator’s documentation is linked below
    operator.itemgetter

    reply
    0
  • 阿神

    阿神2017-04-18 09:54:23

    The answer on the first floor is problematic. Although it will not report an error, it does not have a sorting effect

    Attached below are the feasible methods after verification:

    def sort(a, args):
        return sorted(a, key=lambda x: tuple(x[i] for i in args), reverse=True)
        
    dic_sorted = sort(lst, ['time', 'id', 'type'])
    

    args accepts a list

    reply
    0
  • Cancelreply