python - 如何在尺寸有限的结构中保存有序的独特元素?

标签 python list collections set deque

我需要将元素流保存在一个大小有限的列表中。流中可能有重复的元素,但我只需要保留唯一的元素。此外,当列表的大小超过指定限制时,我需要删除最旧的元素并添加新元素。

我已经尝试过setlistset 的问题是它没有大小限制,如果我想删除最旧的元素,我不知道如何检索它,因为 set 是无序的;但是,它解决了唯一性问题。

另一方面,list 保持项目的顺序,但每当我想插入一个新元素时,我都需要检查可能的重复项,这会花费很多时间。此外,listset 一样不受大小限制。

我的第三个选项可能是 collections.deque 但我不知道它是否保持顺序。有没有办法让 collections.deque 中的项目保持唯一?

这些是我的 list 代码示例:

ids = list()
for item in stream:
    if item not in ids:
        ids.append(item)
    if len(ids) >= len_limit:
        del ids[0]

设置:

ids = set()
for item in stream:
    ids.add(item)
    if len(ids) >= len_limit:
        ids.remove(list(ids)[0])

最佳答案

您可以编写自己的类,同时保留 deque 和 set:

import collections


class Structure:
    def __init__(self, size):
        self.deque = collections.deque(maxlen=size)
        self.set = set()

    def append(self, value):
        if value not in self.set:
            if len(self.deque) == self.deque.maxlen:
                discard = self.deque.popleft()
                self.set.discard(discard)
            self.deque.append(value)
            self.set.add(value)

s = Structure(2)
s.append(1)
s.append(2)
s.append(3)
s.append(3)
print(s.deque)  # deque([2, 3], maxlen=2)

关于python - 如何在尺寸有限的结构中保存有序的独特元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58008416/

相关文章:

python - 使用条件或错误处理返回字符串中的特定字符

python - 使用 getattr [ python ] 在实例上调用方法

python - 如何用时序图展示一个类和另一个以类的实例作为输入的类的关系?

jquery - 如何在不刷新页面的情况下在 flask 中创建链式选择字段?

Python:循环后为存储在变量中的每个单词评分

python - 在Python中使用数组以更方便的方式编写长switch语句

Python 使用随机/选择仅输出一次字符串

java - 使用比较器返回具有最大值的对象

c# - 使用循环从列表中获取唯一值,然后添加另一个值

c# - 如何: Define a Self Referenced Type Property with Reflection Emit in c#