How can i implement a C like struct,create an array of such a struct and read such data in Python?
typedef struct Pair{
int first_element,second_element;
}Pair;
Pair array_of_pairs[10];
2 Answers 2
Python arrays can contain anything - and they grow as needed so you don't need to put a hard-limit on the size.
Try this - it creates a namedtuple (good way to represent struct like things).
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)
answered Apr 12, 2019 at 16:09
rdas
21.4k6 gold badges39 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Neri-kun
And if I,for example,want to print just the first pair or any other data from my array is it enough to just type
print(list_of_pairs[0]) just like in any python list,which i explicitly convert it into an array?rdas
List indexing works just like in C. But you'll get an
IndexError if you try to access anything outside the bounds of the listDave X
collections not collection. Try: from collections import namedtupleUse tuples:
pair = (1, 2)
first, second = pair
array_of_pair = [pair, (3, 4)]
answered Apr 12, 2019 at 16:09
thebjorn
27.6k12 gold badges107 silver badges152 bronze badges
Comments
default