【问题标题】:Python - Safe Indexing with booleanPython - 使用布尔值进行安全索引
【发布时间】:2016-02-16 13:38:20
【问题描述】:

我有一些代码可以从列表中返回值。我正在使用强类型遗传编程(使用优秀的 DEAP 模块),但我意识到10TrueFalse 相同。这意味着如果一个函数需要一个整数,它可能会以一个布尔函数结束,这会导致一些问题。

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

list[1] 返回2

list[True] 也返回 2

有没有 Pythonic 的方法来防止这种情况发生?

【问题讨论】:

  • 你想为data[True]返回什么(顺便说一下,不要命名变量list。Python取了所有好名字,所以把my放在你的变量前面) ?
  • 为什么要使用布尔值作为列表索引?
  • 或者只是使用isinstance(index, int)检查索引变量的类型,然后继续。
  • 可以添加条件来检查索引的类型:if type(index) is int: or if type(index) is bool:

标签: python list indexing boolean deap


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 2018-07-06
    • 2012-09-25
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多