python boolean list_在Python中list[True],list[False]是否有合法的使用?

如果您不明白为什么bool是一个有效的索引参数:这只是为了使bool是{}的子类而在Python中它是一个数值类型。在

如果你问为什么bool首先是一个数字类型,那么你必须明白bool在旧版本的Python中并不存在,人们转而使用int。在

我将补充一些历史性的论点。首先,在Guido van Rossum(又名BDFL)blogpost:The History of Python: The history of ^{}, ^{} and ^{}中对python中bool的添加进行了简要描述。类型是通过PEP 285添加的。在

政治公众人物计划包含用于该决策的实际理由。我将引用下面的政治公众人物部分。在4) Should we strive to eliminate non-Boolean operations on bools

in the future, through suitable warnings, so that for example

True+1 would eventually (in Python 3000) be illegal?

=> No.

There's a small but vocal minority that would prefer to see

"textbook" bools that don't support arithmetic operations at

all, but most reviewers agree with me that bools should always

allow arithmetic operations.6) Should bool inherit from int?

=> Yes.

In an ideal world, bool might be better implemented as a

separate integer type that knows how to perform mixed-mode

arithmetic. However, inheriting bool from int eases the

implementation enormously(in part since all C code that calls

PyInt_Check() will continue to work this returns true for

subclasses of int). Also, I believe this is right in terms of

substitutability: code that requires an int can be fed a bool

and it will behave the same as 0 or 1. Code that requires a

bool may not work when it is given an int; for example, 3 & 4

is 0, but both 3 and 4 are true when considered as truth

values.Because bool inherits from int, True+1 is valid and equals 2, and

so on. This is important for backwards compatibility: because

comparisons and so on currently return integer values, there's no

way of telling what uses existing applications make of these

values.Because of backwards compatibility, the bool type lacks many

properties that some would like to see. For example, arithmetic

operations with one or two bool arguments is allowed, treating

False as 0 and True as 1. Also, a bool may be used as a sequence

index.

I don't see this as a problem, and I don't want evolve the

language in this direction either. I don't believe that a

stricter interpretation of "Booleanness" makes the language any

clearer.

摘要:向后兼容性:有很多代码已经使用ints0和{}来表示False和{},其中一些代码在数值计算中使用了这些值。在

拥有一个“非教科书”类型并不是什么大问题

Python社区中的许多人都想要这些特性

BDFL如是说。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值