Is there a way to create an array in python that captures its length?

To display COM port data in real time in python, I need to create a fixed length array, if a new value is received, it stores it at the last index and when the array is full, after the next update, it outputs the value at the first index, In other words, it stores last value of last index value and empty values ​​at first index (to fix the length)

+3


source to share


1 answer


What you described is basically a fixed length queue of two (often called a deque).

You can use Python's built-in detective:

from collections import deque

d = deque(maxlen=2)

for i in range(10):
    d.append(i)
    print(d)

# deque([0], maxlen=2)
# deque([0, 1], maxlen=2)
# deque([1, 2], maxlen=2)
# deque([2, 3], maxlen=2)
# deque([3, 4], maxlen=2)
# deque([4, 5], maxlen=2)
# deque([5, 6], maxlen=2)
# deque([6, 7], maxlen=2)
# deque([7, 8], maxlen=2)
# deque([8, 9], maxlen=2)

      

You can also use appendleft

instead append

:



for i in range(10):
    d.appendleft(i)
    print(d)

# deque([0], maxlen=2)
# deque([1, 0], maxlen=2)
# deque([2, 1], maxlen=2)
# deque([3, 2], maxlen=2)
# deque([4, 3], maxlen=2)
# deque([5, 4], maxlen=2)
# deque([6, 5], maxlen=2)
# deque([7, 6], maxlen=2)
# deque([8, 7], maxlen=2)
# deque([9, 8], maxlen=2)

      


Alternatively, if you want the other way around, you can inherit the list and implement append

yourself. Note the slightly different result:

class MyList(list):
    def __init__(self, max_len, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_len = max_len

    def append(self, obj):
        if len(self) < self.max_len:
            super().append(obj)
        else:
            self.insert(0, obj)  # inserting to the left
            self.pop()           # deleting the last element on the right

li = MyList(2)

for i in range(10):
    li.append(i)
    print(li)

# [0]
# [0, 1]
# [2, 0]
# [3, 2]
# [4, 3]
# [5, 4]
# [6, 5]
# [7, 6]
# [8, 7]
# [9, 8]

      

+5


source







All Articles