Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建以列表作为值的字典,并对列表中的元素进行排序_Python_List_Sorting_Dictionary - Fatal编程技术网

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

Python 创建以列表作为值的字典,并对列表中的元素进行排序,python,list,sorting,dictionary,Python,List,Sorting,Dictionary,我正在构建一个函数,它接受一个包含三种不同类型元素的列表:整数、浮点和字符串。该函数将列表转换为字典,其中包含这三个不同类别的键。然后将原始列表中的每个元素放入相应的键值对中(例如,列表中的所有字符串元素都被分配给“字符串”键)。我能够让它正常工作,但是我无法对字典值(即列表)中的值进行排序。以下是我所拥有的: def list_dict_sort(input_list): mixed_list =['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi

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

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', '']}
理想情况下,我希望避免在这里进行导入(例如运算符),我只是在寻找一种简单/基本的方法来排序值列表。我尝试使用
sort
sorted()
,但不知道如何将它们构建到我已有的内容中。
是否有一种干净的方法可以做到这一点,还是有一种更有效的方法?

您只需检查这些值并对它们进行排序:

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

请注意,您还可以使用混合元素的
类型
作为字典键,这样就可以在插入元素时直接从元素中计算出来,这样在以后检索时,您就不需要知道特殊的字符串(例如,“等等,我是否使用了'integer'或'int'作为键?”)


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

这里是一个通过and实现的最简解决方案。使用
SortedList
,您的列表将保证始终被排序

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

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)})

插入每个元素时,可以使用
对分.insert
。但是,您必须执行
导入对分
。有关更多详细信息,请参阅。是否有方法将sorted或sort()添加到我的当前脚本中?请查看此方法是否有效(未测试)。替换
sorted_dict['integer']。通过
bisect.in(sorted_dict['integer'],x)
追加(x)
。浮点数和字符串也是如此。然后删除行
sorted_dict.sort
。我尝试了这个,它返回{'float':[],'integer':[],'string':[]}@David这确实有效。请编辑您的问题,以显示您是如何将此代码段集成到代码中的,我将尝试查看出了什么问题。在我的选项中,使用
type(value)
作为键不是一个好主意。考虑<代码> NoMy.FulAT64(5.1321)< /代码>,类型将作为<代码> NUMPY。始终使用
isinstance
并维护显式映射。@jp_data_analysis但是如果您想要
np.float64
的一个键,它与
float
的键不同,该怎么办?如果您不希望这两个键是不同的,那么首先要对混合列表中的元素进行类型转换。我同意它可以是具体的应用程序,哪种方式更好。但是用
isinstance
解析类型值本身没有更好的方法。。。特别是考虑到实例和子类检查也可以用元类重写。因此,如果有人依赖于来自iInstance的键,那么实际的元素可能无法通过duck键入。我不是在假设用户想要什么。例如,有许多答案可以解释为什么在类型检查中合并继承是一个很好的假设
isinstance
并不完美,没有什么是完美的,但它被认为比
type()
更好。您是否认为不应将
float
int
的子类视为
float
int
?@jp_data_analysis我的观点是,使用
isinstance
作为检查类型是否为
int
的方法不太明确,因为自定义对象可能会以一种破坏事物的方式重写实例检查。例如,如果您计划稍后处理
int
元素,但其中一个是不支持所有
int
操作的自定义类(但被自定义为返回
True
,用于
isinstance(…,int)
,则这一切都会成为一个巨大的黑匣子问题。但如果条目仅根据
类型存储,则它是显式的,因为用户必须提前显式转换类型。
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)})