[Diaoye learns programming] MicroPython manual’s built-in module ucollections

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small, and the memory usage is small, which is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

The application scenarios of MicroPython include:
1. Quickly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Pay attention to the following when using MicroPython:
1. The memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here

MicroPython's built-in module ucollections is a module that provides advanced collection and container types.

Its main features are:

It is based on CPython's collections module, but only implements some of its functions, such as deque, namedtuple, OrderedDict, etc.
It can define and operate complex data structures, such as double-ended queues, named tuples, ordered dictionaries, etc., thereby improving data organization and processing capabilities.
It supports different data types and attributes, such as bit fields, pointers, endianness, etc., thereby increasing data flexibility and compatibility.
It provides some convenient functions and methods, such as uctypes.sizeof(), uctypes.addressof(), uctypes.struct(), uctypes.bytearray_at(), etc.

The application scenarios of ucollections module are:

When you need to process complex or ordered data collections, you can use the ucollections module to create and manipulate deque, namedtuple, OrderedDict and other objects to improve efficiency and readability.
When you need to interact with binary files or hardware registers, you can use the ucollections module to define and access data structures, enabling low-level data programming.
When you need to optimize memory usage or performance, you can use the ucollections module to define and manipulate compact data structures, saving space and time.

Things to note about the ucollections module are:

Before using the ucollections module, you need to import it, such as import ucollections.
When defining a data structure, you need to specify the offset, type, size and other attributes of each field, as well as the endianness and alignment of the entire structure.
When accessing data structures, you need to use dot syntax or subscript syntax to refer to subfields or array elements, and use the functions and methods provided by the ucollections module to get or modify data values.
When using the ucollections module, you need to pay attention to memory safety and error handling, avoid accessing illegal or invalid memory addresses, and catch exceptions that may be thrown.

Several practical application examples of the ucollections module are:

Case 1: Create a double-ended queue, add or delete elements at both ends, and then print out the length and content of the queue.

import ucollections

# 创建一个双端队列,并指定其最大长度为5
dq = ucollections.deque((), 5)

# 在队列右端添加元素
dq.append(1)
dq.append(2)
dq.append(3)

# 在队列左端添加元素
dq.appendleft(4)
dq.appendleft(5)

# 打印出队列的长度和内容
print(len(dq), list(dq)) # 输出 5 [5, 4, 1, 2, 3]

# 在队列右端删除元素
dq.pop()

# 在队列左端删除元素
dq.popleft()

# 打印出队列的长度和内容
print(len(dq), list(dq)) # 输出 3 [4, 1, 2]

Case 2: Define a named tuple type, create two objects of this type, and then access their field values ​​through attribute names or indexes.

import ucollections

# 定义一个命名元组类型,并指定其名称和字段名
Point = ucollections.namedtuple("Point", ("x", "y"))

# 创建两个Point类型的对象,并初始化其字段值
p1 = Point(1, 2)
p2 = Point(3, 4)

# 通过属性名访问字段值
print(p1.x, p1.y) # 输出 1 2
print(p2.x, p2.y) # 输出 3 4

# 通过索引访问字段值
print(p1[0], p1[1]) # 输出 1 2
print(p2[0], p2[1]) # 输出 3 4

Case 3: Create an ordered dictionary and traverse its key-value pairs in the order of addition, then modify one of the key-value pairs and traverse again.

import ucollections

# 创建一个有序字典,并按照添加的顺序初始化其键值对
od = ucollections.OrderedDict([("a", 1), ("b", 2), ("c", 3)])

# 按照添加的顺序遍历键值对
for k, v in od.items():
    print(k, v) # 输出 a 1 b 2 c 3

# 修改其中的一个键值对
od["b"] = 4

# 再次按照添加的顺序遍历键值对
for k, v in od.items():
    print(k, v) # 输出 a 1 b 4 c 3

Case 4: Use of deque double-ended queue:

import ucollections

# 创建双端队列
deque = ucollections.deque(maxlen=5)

# 向队列添加元素
deque.append(1)
deque.append(2)
deque.append(3)

# 从队列两端弹出元素
print(deque.popleft())  # 输出: 1
print(deque.pop())  # 输出: 3

# 遍历队列中的元素
for item in deque:
    print(item)

In this example, we create a deque using the deque class of the ucollections module. We can use the append() method to add elements to the end of the queue, and the popleft() and pop() methods to pop elements from the left and right ends of the queue respectively. The double-ended queue also supports iterative operations, and you can use a for loop to traverse the elements in the queue.

Case 5: Use of namedtuple named tuples:

import ucollections

# 定义命名元组
Person = ucollections.namedtuple("Person", ["name", "age", "gender"])

# 创建命名元组实例
person1 = Person("Alice", 25, "female")
person2 = Person("Bob", 30, "male")

# 访问命名元组的字段
print(person1.name)  # 输出: Alice
print(person2.age)  # 输出: 30

In this example, we use the namedtuple function of the ucollections module to define a named tuple Person, which contains three fields: name, age, and gender. We can create instances using the defined named tuples and access the corresponding values ​​by field names.

Case 6: Use of Counter:

import ucollections

# 创建计数器
counter = ucollections.Counter()

# 更新计数器
counter.update([1, 2, 3, 1, 2, 1])

# 获取元素的计数
print(counter[1])  # 输出: 3
print(counter[2])  # 输出: 2

# 获取计数器中的所有元素及其计数
for item, count in counter.items():
    print(item, count)

In this example, we create a counter using the Counter class of the ucollections module. We can update the counter using the update() method, passing in an iterable object as input. We can then get the count of elements via the index operator []. Counters also provide the items() method for iterating through all elements in the counter and their counts.

Case 7: Use deque to implement circular buffer

import ucollections

# 创建一个循环缓冲区,最大容量为 5
buffer = ucollections.deque(5)

# 向循环缓冲区添加元素
buffer.append(1)
buffer.append(2)
buffer.append(3)

# 从循环缓冲区读取元素
print(buffer.popleft())  # 输出: 1
print(buffer.popleft())  # 输出: 2

In this example, we use ucollections.deque to create a circular buffer with a maximum capacity of 5. We can add elements to the buffer using the append method and read elements from the buffer using the popleft method. When the buffer is full, new elements will overwrite the earliest added elements, thus achieving a looping effect.

Case 8: Use Counter to count element frequencies

import ucollections

# 创建一个 Counter 对象
counter = ucollections.Counter()

# 统计元素频次
data = [1, 2, 1, 3, 2, 1, 4, 2, 1]
for item in data:
    counter[item] += 1

# 打印元素频次
print(counter)  # 输出: Counter({1: 4, 2: 3, 3: 1, 4: 1})

In this example, we create a counter object using ucollections.Counter. We can count the frequency of an element by iterating through the data list and using the counter object's key to increment the count value of the corresponding element. Finally, we can print the counter object to see the frequency of each element.

Case 9: Use namedtuple to create named tuples

import ucollections

# 创建一个命名元组类型
Person = ucollections.namedtuple("Person", ["name", "age", "city"])

# 创建一个命名元组对象
person1 = Person("Alice", 25, "New York")
person2 = Person("Bob", 30, "London")

# 访问命名元组对象的字段
print(person1.name)  # 输出: Alice
print(person2.city)  # 输出: London

In this example, we use ucollections.namedtuple to create a named tuple type Person, defining the fields named "name", "age" and "city". We can then use this named tuple type to create multiple named tuple objects, each containing corresponding field values. By accessing the fields of a named tuple object, we can get and manipulate the corresponding values.

These cases demonstrate the practical application of the ucollections module, including using deque to implement circular buffers, using Counter to count element frequencies, and using namedtuple to create named tuples. By using the ucollections module, you can easily use various collection data structures and algorithms on MicroPython devices to meet different programming needs. Please note that when using the ucollections module, you can refer to MicroPython's documentation for more details and usage of each data structure and algorithm.

Insert image description here

おすすめ

転載: blog.csdn.net/weixin_41659040/article/details/132787981