Reputation: 75
I want to make an array which contains arrays of pairs (C++ like pairs) of different sizes, any idea how to do it in python?
To be more specific, I need to know the equivalent to this C++ code in python:
vector<vector<pair<int, int>>> my_vector;
Upvotes: 1
Views: 23664
Reputation: 683
You can implement pairs with tuples, which can be created by separating elements with commas, usually with parenthesis enclosing them for better readability.
For the vectors, you can use lists which allow you to remove and add elements to them as you see fit. These are created with comma separated elements enclosed in square brackets.
An example of implementing your type of structure would be:
pair1 = (0, 1)
pair2 = (4, 3)
inner_vector1 = [pair1, pair2]
inner_vector2 = [pair2]
inner_vector2.append(pair1)
outer_vector = [inner_vector1, inner_vector2]
Which results in the object:
[[(0, 1), (4, 3)], [(4, 3), (0, 1)]]
Which can be visualized as:
outer_vector (list)
{
inner_vector1 (list)
{
pair1, (tuple)
pair2 (tuple)
},
inner_vector2 (list)
{
pair2, (tuple)
pair1 (tuple)
}
}
Upvotes: 8
Reputation: 672
my_vector = [] # python list, for list of lists: use [[]]
my_vector.append([(3,5),(-2,1)]) # my_vector = [[(3,5),(-2,1)]]
my_vector.append([(8,4)]) # my_vector = [[(3,5),(-2,1)],[(8,4)]]
my_vector[1].append((-1,1)) # my_vector = [[(3,5),(-2,1)],[(8,4),(-1,1)]]
my_vector[0].pop() # my_vector = [[(3,5)],[(8,4),(-1,1)]]
my_vector.pop() # my_vector = [[(3,5)]]
append()
is similar to push_back()
method for C++ vector
.
pop()
is the same thing as pop()
method for C++ vector
.
()
is used in place of make_pair()
in C++ pair
Hope this clear it all.
Upvotes: 3
Reputation: 57
In Python we call vector as list.
To construct a list, use
l = []
.
To construct an empty list of list, use ll = [[]]
To construct an empty list of list of tuple, First, you need a list of list, uselll = [[]]
. Then you construct a pair, in Python we call it tuple. Say we have a tuple t = (3, 9)
. Then we may append this tuple to our lll
==> Use lll[0].append(t)
.
Print out lll
, we get [[(3, 9)]]
.
Upvotes: 1