【问题标题】:How to sort a list by the number of items in another list that is inside dict, with keys similar to the first list如何按字典内另一个列表中的项目数对列表进行排序,键类似于第一个列表
【发布时间】:2022-02-08 21:57:26
【问题描述】:

如何根据 dict 中另一个列表的元素数量对列表进行排序(dict 的键与应排序的列表元素相似)。

这是我要排序的列表:list_to_sort = ['a','b','c','d'] 这是一个包含元素的字典:reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}

我应该得到list_after_sort = ['d','a', 'b', 'c']

【问题讨论】:

    标签: python


    【解决方案1】:

    在sorted 函数中使用key 可以传递用于对元素进行排序的函数。

    This answer 涵盖了有用的信息。

    你可以使用:

    list_to_sort = ['a','b','c','d']
    reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}
    sorted(list_to_sort, key = lambda x: sum(reference_dict[x]))
    
    # ['d', 'a', 'b', 'c']
    

    【讨论】:

    • 但是如果不是 [1,1,0,0,0,0] 而是 ['element', 'element, None, None, None]。这种情况该怎么办?
    • 将密钥替换为key = lambda x: sum([e is not None for e in reference_dict[x]])
    【解决方案2】:

    您可以使用sorted 的key 参数来传递任意函数。

    在这种情况下,从字典和sum 中获取值:

    list_after_sort = sorted(list_to_sort, key=lambda x: sum(reference_dict[x]))
    

    输出:['d', 'a', 'b', 'c']

    使用真实值:
    reference_dict = {'a':[1,0,0,'X',0],
                      'b':[1,0,0,0,1,1],
                      'c':[1,1,1,1,0],
                      'd':['element', 'element', None, None, None]}
    
    sorted(list_to_sort, key=lambda x: sum(map(bool, reference_dict[x])))
    # ['a', 'd', 'b', 'c']
    
    使用对象黑名单
    blacklist = set([0, None, 'None'])
    
    sorted(list_to_sort, key=lambda x: sum(e not in blacklist
                                           for e in reference_dict[x]))
    

    【讨论】:

    • 但如果不是[1,1,0,0,0,0] 而是['element', 'element, None, None, None]。这种情况该怎么办?
    • 但如果 None 写成 'None' ?
    • @SOthing 这就是为什么你需要想出一个明确的逻辑来判断什么应该计算。你能详细说明你的情况吗?
    • 我需要计算所有不是“无”的元素。我不认为我可以详细说明
    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多