python - 如何实现位置感知项的 python 列表

标签 python list data-structures

我有一个特定的列表项目需要知道的特殊情况(有一个属性/特性),它告诉:

  • 该项目是否是列表中的最后一项
  • 他们在列表中的索引或“枚举器”

我能想到的方法是:

  1. 重写 __setitem____add__insertappendpop 等。所有
  2. 不是将它们存储在 python 列表中,而是有一个指向下一项的“next”属性。
  3. 添加辅助函数以在评估前(或更新后)同步索引属性
  4. 不要将它们存储为属性,而是在类的“外部”进行处理

1) 看起来像大多数 pythonic 方法,但需要覆盖相当多的方法。 2) 存在必须重新实现上述方法的问题(如果我想使用 insert()pop(),对索引没有真正的帮助) 3) 和 4) 有“你必须记得在做 Y 之前先调用 X”的陷阱

上述列表中的所有项目将(或应该)始终是同一类的实例。

是否有已知的设计模式或我不知道的 pythonic 方法?

最佳答案

我同意 Marcin 的观点,因为您不应该需要它。但无论出于何种不明原因,如果您真的真的确实需要此功能,那么这是一个不错的开始:

class Node:
    def __init__(self, data):
        self.data = data
        self.index = 0
        self.next = None

class myContainer:
    def __init__(self, node):
        self.head = node
        self.length = 1
    def __setitem__(self, i, node):
        if i > self.length:
            raise ValueError("Index %s is too large. Cannot set item at that index. Current container length is %s" %(i, self.length))
        curr = self.head
        while i>0:
            curr = curr.next
            curr.next, node.next = node, curr.next
            node.index = curr.index + 1
        curr = node.next
        while curr is not None:
            curr.index += 1
            curr = curr.next

关于python - 如何实现位置感知项的 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18727192/

相关文章:

database - 数据库中 B 树索引的空间复杂度

c++ - 判断两棵树是否同构

python - 纯Python中dict的求和和计数列表

r - 将自定义函数应用于 DF 列表,将另一个列表作为输入 - R

java - 删除列表的一部分并在成功时返回 true 的方法的正确语法是什么?

algorithm - 哪种数据结构可以在 O(logn) 时间内找到给定附加条件的最大对象?

python - 反转 'user',参数为 '(' ', )' not found. 1 pattern(s) tried: [' project/users/(?P<user_id>[0-9]+)/$']

python - 将 pandas dataframe json 列切成列

python - 如果或 elif 要么为真,则做某事

python - Scikit-learn MLPRegressor - 如何不预测负面结果?