Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

boolean - Is there any legitimate use of list[True], list[False] in 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.

Can anyone think of a legit use of indexing lists with True or False?

question from:https://stackoverflow.com/questions/38117555/is-there-any-legitimate-use-of-listtrue-listfalse-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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'

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...