Python基础必掌握的利用Booleans优化代码巧妙方法

Python基础必掌握的利用Booleans优化代码巧妙方法,第1张

学Python数据科学,玩游戏、学日语、搞编程一条龙。

整套学习自学教程中应用的数据都是《三國志》、《真·三國無雙》系列游戏中的内容。

布尔类型是 Python 的内置数据类型之一。用于表示表达式的真与假。对于复杂冗长的代码,往往可以使用 Booleans 的方式极大的优化和简化,让代码更加易懂,易改写。

文章目录
  • Python 布尔类型
  • 布尔运算符
  • 比较运算符
  • Python 布尔测试

Python 布尔类型

Python Boolean 类型只有 True 和 False 两个可能。

可以通过内置参数查看布尔类型。

type(False)
<class 'bool'>
type(True)
<class 'bool'>

Python 布尔值作为关键字

布尔值可以分配给变量,但不能将值分配给 True 。

var = True
var
True

True 是关键字因此不能赋值,相同的规则适用于 False。

True = 5
  File "", line 1
SyntaxError: cannot assign to True

Python 布尔值作为数字

布尔值在 Python 中被视为数字类型,可以将算术运算应用于布尔值,也可以将它们与数字进行比较。

True == 1
True

False == 0
True

True + (False / True)
1.0

lines = """絶世の美女で、歌舞に優れていた。\n\r
司徒・王允のもとで実の娘同然に育てられる。
"""

line_list = lines.splitlines()
line_list 
['絶世の美女で、歌舞に優れていた。', '', '司徒・王允のもとで実の娘同然に育てられる。']

"絶世の美女" in line_list[0]
True

"絶世の美女" in line_list[1]
False

0 + False + True 
1

["絶世の美女" in line for line in line_list]
[True, False, False]

True + False + False # 等价于  1 + 0 + 0
1

len(line_list)
3
布尔运算符

Python 布尔值只有两个可能的选项 True 或 False,因此可以根据它们分配给每个可能的输入组合的结果来完全指定运算符。

无输入的运算符,可以将 True 和 False 视为不接受任何输入的布尔运算符。其中一个运算符总是返回True,另一个总是返回False。

布尔 not 运算符。

Anot AIdentityYesNo
TrueFalseTrueTrueFalse
FalseTrueFalseTrueFalse

布尔 and 运算符

ABA and B
TrueTrueTrue
FalseTrueFalse
TrueFalseFalse
FalseFalseFalse

布尔 or 运算符

ABA or B
TrueTrueTrue
FalseTrueTrue
TrueFalseTrue
FalseFalseFalse
比较运算符

运算符检查两个对象之间是否存在关系,这些称为比较运算符的运算符始终返回布尔值。

等于(==) 和 不等于(!=)。

# 数字的比较
1 == 1
True
1 == 1.0
True
1 == 2
False
1 <> 2
True

顺序比较 > 、>= 、<、<=。

# 字典无顺序,因此无法比较
{1: 3} < {2: 4}
Traceback (most recent call last):
  File "", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'


# 字符串和整数是分开排序,不可比较。
1 <= "1"
Traceback (most recent call last):
  File "", line 1, in <module>
TypeError: '<=' not supported between instances of 'int' and 'str'


# 常规 *** 作
1 <= 1
True

1 < 1
False

2 > 3
False

2 >= 2
True

is 检查对象身份 *** 作符。

x = []
y = []

x is x
True

x is not x
False

x is y
False

x is not y
True

in 检查是否包含成员 *** 作符。

# 数字 *** 作
small_even = [2, 4]

1 in small_even
False

2 in small_even
True

10 in small_even
False

# 字符串 *** 作
"三国志" in "三国時代の歴史書『三国志』"
True
"無双" in "三国時代の歴史書『三国志』"
False

链接比较运算符。

# 比较运算符可以形成链
1 < 2 < 3
True

1 < 2 and 2 < 3
True

1 < 3 < 2
False

1 < 3 and 3 < 2
False

1 < 2 < 1
False

1 == 1.0 < 0.5
False

1 == 1.0 == True
True

1 < 3 > 2
True

1 < 2 < 3 < 4 < 5
True


# 短路链评估
2 < "2"
Traceback (most recent call last):
  File "", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
3 < 2 < "2"
False

# 比较链的短路评估可以防止其他异常
3 < 2 < (1//0)
False

混合运算符和链接。

a = 0
a is a < 1
True

(a is a) < 1
False

a is (a < 1)
False
Python 布尔测试

布尔值最重要的用途是在 if 语句中。判断结果为 True 则该语句将执行。

1 == 1
True

if 1 == 1:
	print("yes")
yes

1 == 2
False

if 1 == 2:
    print("yes")

None 作为布尔值。

bool(None)
False

数字作为布尔值。

# 非零整数都为真
bool(3), bool(-5), bool(0)
(True, True, False)

import math
[bool(x) for x in [0, 1.2, 0.5, math.inf, math.nan]]
[False, True, True, True, True]

序列作为布尔值。

# len(n) 结果为非0、非空都为真。
bool([1]), bool([])
(True, False)

bool((1,2)), bool(())
(True, False)

bool({1,2,3}), bool(set())
(True, False)

bool({1: 2}), bool({})
(True, False)

bool("hello"), bool("")
(True, False)

bool(b"xyz"), bool(b"")
(True, False)

其他类型(def、class)作为布尔值。

# 自定义函数 def 默认为真
def func():
    pass
bool(func)
True

# 自定义类 class 默认为真
class Dummy:
	pass
bool(Dummy())
True

NumPy 数组。

from numpy import array
x = array([0])
len(x)
1
bool(x)
False

运算符(and、or、not)和函数。

not 1
False

not 0
True


# 短路求值,返回真值
1 and 2
2

0 and 1
0

1 or 2
1

0 or 2
2


# all()检查其所有元素
all([1, 2, 3])
True

all([0, 1, 2])
False

# any()检查其所有元素
any([1, 0, 0])
True

any([False, 0, 0.0])
False

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/758861.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-01
下一篇 2022-05-01

发表评论

登录后才能评论

评论列表(0条)

保存