Python安全的布尔索引
我有一些从列表中返回值的代码。我正在使用强类型遗传编程(使用优秀的DEAP模块),但我意识到Python安全的布尔索引,python,list,indexing,boolean,deap,Python,List,Indexing,Boolean,Deap,我有一些从列表中返回值的代码。我正在使用强类型遗传编程(使用优秀的DEAP模块),但我意识到1和0与True和False相同。这意味着当函数需要整数时,它可能会以布尔函数结束,这会导致一些问题 例如: list=[1,2,3,4,5] list[1]返回2 list[True]还返回2 有没有类似python的方法可以防止这种情况发生?您可以定义自己的列表,其中不允许使用布尔索引: class MyList(list): def __getitem__(self, item):
1
和0
与True
和False
相同。这意味着当函数需要整数时,它可能会以布尔函数结束,这会导致一些问题
例如:
list=[1,2,3,4,5]
list[1]
返回2
list[True]
还返回2
有没有类似python的方法可以防止这种情况发生?您可以定义自己的列表,其中不允许使用布尔索引:
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.
>>L1[正确]
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 L1[正确]
在_u获取项目_;(自我,项目)
2定义获取项目(自身,项目):
3如果存在(项目,bool):
---->4 raise TypeError('索引只能是一个整数,但有布尔值')
TypeError:索引只能是一个整数,不能是布尔值。
相应地重写
\uuuu setitem\uuuu
,以防止设置以布尔值作为索引的值。对于数据[True]
(顺便说一下,不要命名变量列表
。Python取了所有好的名称,所以将my
放在变量前面)?为什么要使用布尔值作为列表索引?或者只需使用isinstance(index,int)
检查索引变量的类型并相应地继续。您可以添加一个条件来检查索引的类型:如果类型(index)为int:
或者如果类型(index)为bool: