简体   繁体   English

Python中类似C的结构数组

[英]C-like array of structs in Python

How can i implement a C like struct,create an array of such a struct and read such data in Python? 如何在Python中实现类似C的结构,创建此类结构的数组并读取此类数据?

typedef struct Pair{
int first_element,second_element;
}Pair;


Pair array_of_pairs[10];

Python arrays can contain anything - and they grow as needed so you don't need to put a hard-limit on the size. Python数组可以包含任何内容-并且可以根据需要增长,因此您无需对大小进行硬限制。

Try this - it creates a namedtuple (good way to represent struct like things). 试试这个-它会创建一个namedtuple (表示类似结构的好方法)。

from collection import namedtuple
Pair = namedtuple("Pair", ["first", "second"])

p1 = Pair(1,2)
p2 = Pair(3,4)

list_of_pairs = [p1,p2]

print(list_of_pairs)

Use tuples: 使用元组:

pair = (1, 2)
first, second = pair
array_of_pair = [pair, (3, 4)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM