如何在python中创建排序列表或字典?

如何在python中创建排序列表或字典?,python,Python,我想创建一个字符串列表,元素按字符串长度排序。例如: my_list = ['a', 'bc', 'fef', 'cde', 'xxxx'] 当我将一个元素插入到这个初始的空my_列表中时,如何保持这样的顺序?在Java中,我可以创建一个定制的order函数,并将其作为构造函数参数传递 我发现这是最简单的方法: l = sorted(my_list, key=str.__len__) 您可以使用带有heapq模块的列表来保持其“排序”* 要提供自定义排序功能,可以使用小型包装器: class

我想创建一个字符串列表,元素按字符串长度排序。例如:

my_list = ['a', 'bc', 'fef', 'cde', 'xxxx']
当我将一个元素插入到这个初始的空my_列表中时,如何保持这样的顺序?在Java中,我可以创建一个定制的order函数,并将其作为构造函数参数传递

我发现这是最简单的方法:

l = sorted(my_list, key=str.__len__)

您可以使用带有
heapq
模块的列表来保持其“排序”*

要提供自定义排序功能,可以使用小型包装器:

class Heap(list):
    """
    A lightweight heap essentially utilizing the heapq module.
    It can however be supplied a key argument on initialization. The heap
    itself is a list of tuples of (key, element), but popping is transparent.
    """

    def __init__(self, initial=None, key=lambda x: x):
        """
        Return an empty heap.
        If it has the argument 'initial', it is assumed to be an iterable from
        which the heap will be initialized.
        'key' is a function similar to those usable in the sort() function,
        which will be used whenever a comparison is made.
        """
        self.key = key
        if initial:
            self.extend((key(item), item) for item in initial)
            heapq.heapify(self)

    def push(self, item):
        """Push an element on the heap."""
        heapq.heappush(self, (self.key(item), item))

    def pop(self):
        """Pop the smallest element off the heap, maintaining the invariant."""
        return heapq.heappop(self)[1]

    def replace(self, item):
        """
        Pop an element off the heap, then push.
        More efficient then first popping and then pushing.
        """
        return heapq.heapreplace(self, (self.key(item), item))[1]

    def pushpop(self, item):
        """
        Push an element on the heap, then pop and return the smallest item.
        More efficient then first pushing and then popping.
        """
        return heapq.heappushpop(self, (self.key(item), item))[1]
用法:

>>> my_heap = Heap(['a', 'bc', 'fef', 'cde', 'xxxx'])
>>> my_heap.push('fooooo')


*:堆后面的列表看起来不会排序,但在使用堆接口时会排序。

一种可能的解决方案是使用
对分。此函数将向列表中插入值,同时保持排序顺序:

from collections import UserString
from bisect import insort

class custom_string(UserString):
    def __eq__(self, other):
        return len(self) == len(other)

    def __lt__(self, other):
        return len(self) < len(other)


def insert(lst, s):
    insort(my_list, custom_string(s))

my_list = []

insert(my_list, 'cde')
insert(my_list, 'a')
insert(my_list, 'bc')
insert(my_list, 'xxxx')
insert(my_list, 'fef')

print(my_list)

编辑:
my\u列表
中的值属于类型
custom\u字符串
,具有custom
\uuuuuu eq\uuu
\uu lt\uuu
功能。要将其重新键入到正常字符串,请使用例如
str()

您可以像这样使用SortedList。您可能必须先安装sortedcontainer才能使用它

from sortedcontainers import SortedList
x=['fef', 'cde', 'xxxx','a', 'bc']
sl = SortedList(x,key=lambda x: len(x))
list(sl) #['a', 'bc', 'fef', 'cde', 'xxxx']

你可以简单地按照你在帖子中所说的分类。但是,如果您想在适当的索引处插入一个新的传入元素(根据适当的含义,插入不应干扰不断增加的“长度”标准),那么下面也是一个简单的函数。我假设您已经有了一个列表my_list=['a'、'bc'、'fef'、'cde'、'xxxx'],然后您想从Random_strings=['b'、'ghij'、'fgh']插入新字符串

将numpy导入为np
我的清单=['a'、'bc'、'fef'、'cde'、'xxxx']
随机_字符串=['b','ghij','fgh']
def在适当的索引处添加字符串(列表位置插入,字符串插入):
Diff_of_Length=np.数组([len(x)-len(StringToInsert)表示列表中的x])
适当索引=np。其中(长度的差异==0)[0][0]
插入(适当的索引,StringToInsert)
返回列表wheretoinsert
对于随机字符串中的每个随机字符串:
我的列表=在适当的索引处添加字符串(我的列表,每个随机字符串)
打印(我的列表)
当我运行它时,我会在每次插入后得到一个已经排序的列表。无需在每次插入后进行排序。打印输出如下所示

['b','a','bc','fgh','fef','cde','ghij','xxxx']

只是做同样工作的另一种方法(正如本线程中已经提供的)。在特定情况下可能对某人有用。在这种情况下,您已经找到了解决方案,恭喜

你可以这样做。虽然这样做有效,但最糟糕的时间复杂度是糟糕的(因为当对分在对数时间内找到插入字符串的位置时,插入字符串是线性的)。可能对OP来说是个问题,也可能不是。
['a', 'bc', 'cde', 'fef', 'xxxx']
from sortedcontainers import SortedList
x=['fef', 'cde', 'xxxx','a', 'bc']
sl = SortedList(x,key=lambda x: len(x))
list(sl) #['a', 'bc', 'fef', 'cde', 'xxxx']