the a only Allowed containing 0 1 2 ,
a=[0,1,2]#a's max size开发者_高级运维
if a=[0,] a += [1] --> [0,1]
if a=[0,1] a += [1] --> [0,1]
if a=[0,1] a += [2] --> [0,1,2]
if a=[0,1,2] a += [1] --> [0,1,2]
if a=[0,1,2] a += [4] --> [0,1,2]
so what can i do
You can always create you own class that does what you need: EDIT:
class LimitedList:
def __init__(self, inputList=[]):
self._list = []
self.append(inputList)
def append(self, inputList):
for i in inputList:
if i in [0,1,2] and i not in self._list:
self._list += [i]
return self._list.sort()
def set(self, inputList=[]):
self.__init__(inputList)
def get(self):
return self._list
def __iter__(self):
return (i for i in self._list)
def __add__(self, inputList):
temp = LimitedList(self._list)
for i in inputList:
if i in [0,1,2] and i not in temp._list:
temp._list += [i]
temp._list.sort()
return temp
def __getitem__(self, key):
return self._list[key]
def __len__(self):
return len(self._list)
a = LimitedList([2,3,4,5,6,0]) # create a LimitedList
print a.get() # get the LimitedList
a += [2,3,4,5,6,6,1] # use the "+" operator to append a list to your limited list
print len(a) # get the length
print a[1] # get the element at position 1
for i in a: # iterate over the LimitedList
print i
I added some descriptors to that you can directly use the +
operator like you wanted, and you can also iterate over the list and use the in
operator, get the length with len()
, and access the elements, you can add more if you want and create you own customized list type.
For more info you can check the Data model page
You must be doing something wrong:
>>> a = [0, 1, 2]
>>> a += [4]
>>> a
[0, 1, 2, 4]
>>> _
you need to subclass list, and modify _ _ iadd__ (at least). but I haven't yet figured out exactly how. stay tuned...
精彩评论