【问题标题】:Unable to sort the dictionary of list by keys alphabetically using the lambda function无法使用 lambda 函数按字母顺序对列表字典进行排序
【发布时间】:2019-09-14 19:40:00
【问题描述】:

我有这个列表的字典

Dict = {'Language': ['german', 'hindi', 'arabic', 'spanish'], 'Auto': ['porsche', 'bmw', 'jaguar', 'chrysler'], 'Mobile': ['nokia', 'apple', 'asus', 'samsung']}

在按值对字典进行排序后,我希望 o/p 为:

{'Language': ['arabic', 'german', 'hindi', 'spanish'], 'Auto': ['bmw', 'chrysler', 'jaguar', 'porsche'], 'Mobile': ['apple', 'asus', 'nokia', 'samsung']}

所有列表元素按字母顺序排序。我尝试在 sorted 函数中使用 lambda 函数,但它不起作用。因此,有人可以看看并纠正我的一小段代码..

sorted(Dict.items(), key = lambda t: t[1][0])

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    试试字典理解

    例如

    dict1 = {'Language': ['german', 'hindi', 'arabic', 'spanish'], 'Auto': ['porsche', 
            'bmw', 'jaguar', 'chrysler'], 'Mobile': ['nokia', 'apple', 'asus', 
            'samsung']}
    
    reuslt = { k: sorted(v) for k,v in dict1.items() }
    print(reuslt)
    

    或者用 lambda 映射

    reuslt  = dict(map(lambda kv: (kv[0], sorted(kv[1])), dict1.items()))
    print(reuslt)
    

    O/P:

    {'Language': ['arabic', 'german', 'hindi', 'spanish'], 'Auto': ['bmw', 'chrysler',
       'jaguar', 'porsche'], 'Mobile': ['apple', 'asus', 'nokia', 'samsung']}
    

    【讨论】:

    • 不能用 lambda 排序吗?
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2011-04-10
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多