布尔值和布尔代数的表示完全一致,一个布尔值只有True
、False
两种值,要么是True
,要么是False
,在Python中,可以直接用True
、False
表示布尔值(请注意大小写),也可以通过布尔运算计算出来:
>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
布尔值可以用and
、or
和not
运算。
and
运算是与运算,只有所有都为True
,and
运算结果才是True
:
>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True
or
运算是或运算,只要其中有一个为True
,or
运算结果就是True
:
>>> True or True
True
>>> True or False
True
>>> False or False
False
>>> 5 > 3 or 1 > 3
True
not
运算是非运算,它是一个单目运算符,把True
变成False
,False
变成True
:
>>> not True
False
>>> not False
True
>>> not 1 > 2
True
布尔值经常用在条件判断中,比如:
if age >= 18:
print('adult')
else:
print('teenager')
所有的数据类型自带布尔值,只有0,None,空的布尔值为False
定义集合: 集合内的元素必须是唯一的; 集合内的元素必须是可hash的,也是就不可变类型; 集合是无序的。
集合的作用一:关系运算; 集合的作用二:去重。
{1,2,3,1}
或
定义可变集合set
>>> set_test=set('hello')
>>> set_test
{'l', 'o', 'e', 'h'}
改为不可变集合frozenset
>>> f_set_test=frozenset(set_test)
>>> f_set_test
frozenset({'l', 'e', 'h', 'o'})
python_s={‘egon’,’alex’,’钢蛋’,’老王’}
linux_s={‘alex’,’钢蛋’,’欧德博爱’,’艾里科四’}
python_s & linux_s 交集
python_s | linux_s 并集
取只报名了python课程的学生:差集
python_s – linux_s
取只报名了linux课程的学生:差集
linux_s – python_s
取没有同时报名python和linux课程的学:对称差集
linux_s ^ python_s
python_s.intersection(linux_s) 交集
python_s.union(linux_s) 并集
python_s.difference(linux_s)) 差集#python_s-linux_s
python_s.symmetric_difference(linux_s) 对称差集,python_s ^ linux_s
python_s.difference_update(linux_s) 将linux_s的值更新到python_s的几个集合中
.add() 给集合添加元素
.remove() 删除集合中的元素,无元素会报错
.discard() 删除集合中的元素,不报错
.issubset() 判断是否是子集
.issuperset() 判断是否是父集
.isdisjoint() 判断是否有交集,没有交集返回True
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/167420.html原文链接:https://javaforall.cn