Python 如何实现具有排序功能的类队列容器

Python 如何实现具有排序功能的类队列容器,python,python-3.x,pyqt,pyside,Python,Python 3.x,Pyqt,Pyside,我想要一个固定长度的列表,比如容器,它应该有一个类似sorted()的函数,我可以用它来排序,我想应该还有一个函数,我可以用它来检测其中的项目数量是否达到容器的长度,因为如果其中的项目数量达到容器的长度(固定),我想处理其中的数据。Python中有这样的容器吗?如果没有,应该使用什么基本容器来实现这样的容器 容器类似于队列,但队列没有排序函数如果需要,可以创建自己的容器类。下面是一个非常简单的示例,可以为您指出正确的方向 class MyContainer: def __init__(s

我想要一个固定长度的列表,比如容器,它应该有一个类似sorted()的函数,我可以用它来排序,我想应该还有一个函数,我可以用它来检测其中的项目数量是否达到容器的长度,因为如果其中的项目数量达到容器的长度(固定),我想处理其中的数据。Python中有这样的容器吗?如果没有,应该使用什么基本容器来实现这样的容器


容器类似于队列,但队列没有排序函数

如果需要,可以创建自己的容器类。下面是一个非常简单的示例,可以为您指出正确的方向

class MyContainer:
    def __init__(self, size, key=None, func=None):
        self.size = size
        self.items = []
        self.key = key
        self.func = func

    def add_item(self, item):
        if not self.is_full():
            self.items.append(item)
        else:
            # Handle cases where the container is full, by raising an exception
            # or printing an error message
            #raise Exception('The container is full')
            print("Container is full")
            return
        if len(self.items) == self.size:
            self.sort_items(self.key)
            self.process_items(self.sort)

    def is_full(self):
        return len(self.items) >= self.size

    def sort_items(self, key):
        self.items = sorted(self.items, key=key)

    def process_items(self, func):
        self.items = map(func, self.items)
使用
key=lamba x:len(x)
func=str.lower
调用此函数将根据项目的长度对列表进行排序,并将所有字符串转换为小写

>> c = MyContainer(3, key=lambda x: len(x), func=str.lower)
>> c.add_item('a')
>> c.add_item('aBcD')
>> c.add_item('ab')
>> print(c.items)

['a', 'ab', 'abcd']
这听起来似乎符合规范。这允许以任何顺序(最多)将项目添加到队列中,但随后会按排序顺序将项目从队列中移除:

import queue, random

items = list(range(15))
random.shuffle(items)

pq = queue.PriorityQueue(5)

while items:
    pq.put_nowait(items.pop())
    if pq.full():
        print('processing...')
        while not pq.empty():
            print(pq.get_nowait())
        print()
输出:

processing...
0
4
5
8
14

processing...
1
2
10
11
13

processing...
3
6
7
9
12

总而言之,我想先把容器装满,然后对它进行分类,然后处理里面的所有内容。有什么原因使基本列表不能满足您的需要吗?您可以在写入列表时测试列表的长度。它应该是“队列式”的吗?@peterdegloper它可以有固定的长度,但不包含任何内容。@HughBothwell peterdegloper它可以有固定的长度,但不包含任何内容,还应该有一个功能,我可以使用它来检测是否在它的项目数量达到容器的长度。谢谢你伟大的工作!但我发现queue也可以在这种情况下使用,>>>导入队列>>>a=queue.queue(10)>>>a.put(“asdf”)>>>a.put(“qwer”)>>>a.put(“zxcv”)>>a.put(“1234”)>>排序(a.queue)['1234'、'asdf'、'qwer'、'zxcv']