如何使用python在列表中保存0,1,2

zjm*_*126 -4 python list

a只允许包含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]
Run Code Online (Sandbox Code Playgroud)

所以我能做些什么

P2b*_*2bM 5

您可以随时创建自己的类,满足您的需求: 编辑:

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
Run Code Online (Sandbox Code Playgroud)

我添加了一些描述符,你可以直接使用+你想要的运算符,你也可以迭代列表并使用in运算符,获取长度len(),并访问元素,你可以添加更多,如果你想要并创建自己的自定义列表类型.

有关详细信息,请查看" 数据模型"页面