创建一个以列表作为值的字典,并对列表中的元素进行排序

时间:2018-02-06 21:41:38

标签: python list sorting dictionary

我正在构建一个函数,它接受一个包含三种不同类型元素的列表:整数,浮点数和字符串。该函数将列表转换为字典,其中包含这三个不同类别中的每一个的键。然后将该原始列表中的每个元素放入适当的键值对中(例如,列表中的所有字符串元素都被分配给“字符串”键)。我能够正常工作,但是我无法对字典值(列表)中的值进行排序。这就是我所拥有的:

def list_dict_sort(input_list): 
    mixed_list =['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi', 0, 'yes', 98765., '', 25]
    sorted_dict = {}                 
    sorted_dict['integer'] = []       
    sorted_dict['float'] = []
    sorted_dict['string'] = []
    for x in mixed_list:           
        if "int" in str(type(x)):  
            sorted_dict['integer'].append(x) 
        elif "float" in str(type(x)):
            sorted_dict['float'].append(x)
        elif "str" in str(type(x)):
            sorted_dict['string'].append(x)
    sorted_dict.sort
    return(sorted_dict)

list_dict_sort(mixed_list)

返回:

{'float': [123.45, 3.0, 98765.0],
 'integer': [33, 890, 0, 25],
 'string': ['asdf', 'qwerty', 'hi', 'yes', '']}

结构上这个函数让我得到了我想要的东西,除了值列表被排序。我想要的确切输出是:

{'float': [3.0, 123.45, 98765.0],
 'integer': [0, 25, 33, 890],
 'string': ['asdf', 'hi', 'qwerty',  'yes', '']}

理想情况下,我想避免在这里进行导入(例如运算符),我只是在寻找一种简单/基本的方法来对值列表进行排序。我尝试使用sortsorted(),但无法弄清楚如何将它们构建到我已有的内容中。 有没有一种干净的方法可以做到这一点还是有更有效的方式?

3 个答案:

答案 0 :(得分:2)

您可以查看这些值并对其进行排序:

for v in sorted_dict.values():
    v.sort();

答案 1 :(得分:1)

请注意,您还可以使用混合元素的type作为字典键,因此可以在插入元素时直接从元素计算,因此在以后检索时,您不需要要知道一个特殊的字符串(例如“等待,我是否使用'整数'或'int'作为密钥?”)...

In [4]: from collections import defaultdict

In [5]: d = defaultdict(list)

In [6]: mixed_list = ['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi', 0, 'yes', 98765., '', 25]

In [7]: for value in mixed_list:
   ...:     d[type(value)].append(value)
   ...:     

In [8]: d
Out[8]: 
defaultdict(list,
            {str: ['asdf', 'qwerty', 'hi', 'yes', ''],
             int: [33, 890, 0, 25],
             float: [123.45, 3.0, 98765.0]})

In [9]: for k, v in d.items():
   ...:     v.sort()
   ...:     

In [10]: d
Out[10]: 
defaultdict(list,
            {str: ['', 'asdf', 'hi', 'qwerty', 'yes'],
             int: [0, 25, 33, 890],
             float: [3.0, 123.45, 98765.0]})

在最后一个结果中,请注意默认字符串排序将把''放在前面。你需要编写自己的字符串比较器,如果你需要将它排序到最终位置,它会将任何字符串评估为小于空字符串。

答案 2 :(得分:1)

以下是collections.defaultdictsortedcontainers.SortedList的极简主义解决方案。使用SortedList,您的列表保证始终排序。

注意我还用isinstance替换了类型检查,并为键添加了字典映射类型。这样做的目的是将逻辑与配置/变量分开。

from collections import defaultdict
from sortedcontainers import SortedList

mixed_list = ['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi', 0, 'yes', 98765., '', 25]

def list_dict_sort(input_list): 

    sorted_dict = defaultdict(SortedList)

    mapper = {int: 'integer',
              float: 'float',
              str: 'string'}

    for x in mixed_list:
        for k, v in mapper.items():
            if isinstance(x, k):
                sorted_dict[v].add(x)
                break

    return(sorted_dict)

list_dict_sort(mixed_list)

# defaultdict(sortedcontainers.sortedlist.SortedList,
#             {'float': SortedList([3.0, 123.45, 98765.0], load=1000),
#              'integer': SortedList([0, 25, 33, 890], load=1000),
#              'string': SortedList(['', 'asdf', 'hi', 'qwerty', 'yes'], load=1000)})
相关问题