Python - 使用布尔值的安全索引



我有一些从列表中返回值的代码。我正在使用强类型遗传编程(使用出色的DEAP模块(,但我意识到10TrueFalse相同。这意味着当函数需要整数时,它最终可能会得到一个布尔函数,这会导致一些问题。

例如: list = [1,2,3,4,5]

list[1]返回2

list[True]也返回2

有没有一种 Pythonic 方法来防止这种情况?

您可以定义自己的不允许布尔索引的列表:

class MyList(list):
    def __getitem__(self, item):
        if isinstance(item, bool):
            raise TypeError('Index can only be an integer got a bool.')
        # in Python 3 use the shorter: super().__getitem__(item)
        return super(MyList, self).__getitem__(item)

创建实例:

>>> L = MyList([1, 2, 3])

整数工作:

>>> L[1]
2

True不会:

>>> L1[True]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-888-eab8e534ac87> in <module>()
----> 1 L1[True]
<ipython-input-876-2c7120e7790b> in __getitem__(self, item)
      2     def __getitem__(self, item):
      3         if isinstance(item, bool):
----> 4             raise TypeError('Index can only be an integer got a bool.')
TypeError: Index can only be an integer got a bool.

相应地覆盖__setitem__以防止使用布尔值作为索引设置值。

最新更新