使用布尔函数的Python安全索引

2024-04-26 02:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些从列表中返回值的代码。我使用的是强类型遗传编程(使用优秀的DEAP模块),但是我意识到1&;0与{}和{}是相同的。这意味着当一个函数需要一个整数时,它可能最终得到一个布尔函数,这会导致一些问题。在

例如: ^{cd5}

list[1]返回2

list[True]还返回2

有没有一种Python式的方法来防止这种情况?在


Tags: 模块方法函数代码true类型列表编程
1条回答
网友
1楼 · 发布于 2024-04-26 02:27:09

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

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)

举个例子:

^{pr2}$

整数起作用:

>>> 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__以防止设置布尔值作为索引。在

相关问题 更多 >