Python中有合法使用list [True],list [False]吗? [英] Is there any legitimate use of list[True], list[False] in Python?
问题描述
由于True
和False
是int
的实例,因此以下内容在Python中有效:
Since True
and False
are instances of int
, the following is valid in Python:
>>> l = [0, 1, 2]
>>> l[False]
0
>>> l[True]
1
我理解为什么会这样.但是,我发现这种行为有点出乎意料,并且可能导致难以调试的错误.它肯定咬了我几次.
I understand why this happens. However, I find this behaviour a bit unexpected and can lead to hard-to-debug bugs. It has certainly bitten me a couple of times.
有人能想到合法使用True
或False
的索引列表吗?
Can anyone think of a legit use of indexing lists with True
or False
?
推荐答案
In the past, some people have used this behaviour to produce a poor-man's conditional expression:
['foo', 'bar'][eggs > 5] # produces 'bar' when eggs is 6 or higher, 'foo' otherwise
但是,使用正确的条件表达式添加到Python 2.5的语言中后,由于您指出的原因,人们对此一无所获:依靠布尔值作为整数的子类对于维护人员来说太神奇"了,不易理解.
However, with a proper conditional expression having been added to the language in Python 2.5, this is very much frowned upon, for the reasons you state: relying on booleans being a subclass of integers is too 'magical' and unreadable for a maintainer.
因此,除非您正在进行代码搜寻(故意生成非常紧凑和晦涩的代码),否则请使用
So, unless you are code-golfing (deliberately producing very compact and obscure code), use
'bar' if eggs > 5 else 'foo'
取而代之的是
,它的另一个优点是,它们选择的两个表达式都是 lazily 求值的;如果eggs > 5
为false,则永远不会执行if
之前的表达式.
instead, which has the added advantage that the two expressions this selects between are lazily evaluated; if eggs > 5
is false, the expression before the if
is never executed.
这篇关于Python中有合法使用list [True],list [False]吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!