是否可以禁用跳转到列表的末尾?

时间:2016-03-12 13:49:58

标签: python

在我写的程序中,禁用使用负数跳转到列表末尾的功能非常方便。我的意思是我想要这个:

list = [1, 2, 3, 4]
number = list[-1]
print(number)

不输出4,但是例如给我一个IndexError,就像我试图访问列表中的第5个条目一样。

编程新手,所以不确定是否可以做到这样的事情,但它会省去很多代码。当然我可以解决它,但如果存在这个选项会很好!

3 个答案:

答案 0 :(得分:3)

if index<0:
    value = l[0]
else:
    value = l[index]

list 也是python中的关键字,所以不要像在示例中那样使用它。

答案 1 :(得分:1)

我不完全确定你想通过这样做完成什么,但你可能会尝试覆盖__getitem____setitem__,如下所示:

class NewList(list):
    def __getitem__(self, key):
        if isinstance(key, int) and key < 0:
            raise IndexError("Cannot index to values lower than 0.")
        return super().__getitem__(key)

    def __setitem__(self, key, value):
        if isinstance(key, int) and key < 0:
            raise IndexError("Cannot index to values lower than 0.")
        return super().__setitem__(key, value)

list = NewList

请记住,这样做并不是一个好主意,可能会导致内部问题,所以我不会建议。

答案 2 :(得分:0)

否定索引lst[-1]lst[len(lst)-1]基本相同,这是正索引。所以你想做的事情并没有真正意义,因为这些地方的物品仍然可以进入。

但你仍然可以这样做:

class CustomList(list):
    def __getitem__(self, key):
        if isinstance(key, slice):
            if key.start < 0 or key.stop < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__getitem__(key)
        elif isinstance(key, int):
            if key < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__getitem__(key)
        else:
            raise TypeError("Index must be a slice object or an integer")

    def __delitem__(self, key):
        if isinstance(key, slice):
            if key.start < 0 or key.stop < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__delitem__(key)
        elif isinstance(key, int):
            if key < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__delitem__(key)
        else:
            raise TypeError("Index must be a slice object or an integer")

    def __setitem__(self, key, value):
        if isinstance(key, slice):
            if key.start < 0 or key.stop < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__setitem__(key, value)
        elif isinstance(key, int):
            if key < 0:
                raise TypeError("Negative indexes are not allowed")
            else:
                super(self.__class__, self).__setitem__(key, value)
        else:
            raise TypeError("Index must be a slice object or an integer")

alist = [1, 2, 3, 4]
print(alist[-1])
print(alist[-3:-1])
blist = CustomList([1, 2, 3, 4])
print(blist[1])
print(blist[1:3])
blist[1] = 10
print(blist)
blist[1:3] = [20, 30]
print(blist)
try:
    print(blist[-1])
except TypeError as ex:
    print(ex)
try:
    print(blist[-3:-1])
except TypeError as ex:
    print(ex)
try:
    blist[-1] = 100
except TypeError as ex:
    print(ex)
    print(blist)
try:
    blist[-3:-1] = [200, 300]
except TypeError as ex:
    print(ex)
    print(blist)
try:
    del blist[-1]
except TypeError as ex:
    print(ex)
    print(blist)    
del blist[len(blist)-1]
print(blist)

这将提供以下输出:

4
[2, 3]
None
None
[1, 10, 3, 4]
[1, 20, 30, 4]
Negative indexes are not allowed
Negative indexes are not allowed
Negative indexes are not allowed
[1, 20, 30, 4]
Negative indexes are not allowed
[1, 20, 30, 4]
Negative indexes are not allowed
[1, 20, 30, 4]
[1, 20, 30]