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

时间:2011-04-07 02:39:56

标签: python list

a only Allowed包含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]

所以我该怎么办

3 个答案:

答案 0 :(得分: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

我添加了一些描述符,你可以直接使用+运算符,你也可以迭代列表并使用in运算符,得到{{1}的长度,并访问元素,您可以根据需要添加更多元素,并创建自己的自定义列表类型。

有关详细信息,请查看Data model页面

答案 1 :(得分:1)

你一定做错了什么:

>>> a = [0, 1, 2]
>>> a += [4]
>>> a
[0, 1, 2, 4]
>>> _

答案 2 :(得分:0)

你需要子类列表,并修改_ _ iadd __(至少)。但我还没弄清楚到底是怎么回事。敬请期待......