is there a data structure in python that is equivalent to array in cpp? one that some elements are initialized and some are not? for example, in python list: [1,2,3], elements have to be sequentially filled in cpp array can be a[0] == 0, a1 -- arbitrary, uninitialized, a[2] == 2
is there an cpp-array equivalent structure in python? ps, python array doesn't seem to be equivalent, all elements have to be filled sequentially too
enter image description here
-
By what way it is not "equivalent"? Just because you cannot leave garbage in certain element of list?Adrian Shum– Adrian Shum2016年10月18日 05:19:36 +00:00Commented Oct 18, 2016 at 5:19
2 Answers 2
Perhaps this answer here on StackOverflow may be what you are looking for?
Comments
You can probably put together some kind of wrapper using a dictionary:
class CppArray:
def __init__(self, value):
if value == None:
self.data = {}
self.length = 0
else:
self.data = { 0: value }
self.length = 1
def insert(self, index, value):
while index in self.data:
tmp = self.data[index]
self.data[index] = value
value = tmp
index = index + 1
self.data[index] = value
if index >= self.length:
self.length = index + 1
def __getitem__(self, index):
if (index < 0 or index >= self.length):
# must create IndexException
raise IndexException("Index out of range")
if index in self.data:
return self.data[index]
else:
return None
x = CppArray("i")
x.insert(0,10)
x.insert(200,30)
x[1]
Obviously this quick sketch is missing many details which would make the class more useful.
For other ideas on special methods you could use, check: