一、判断某值是否为真
当在 if 或者 while 语句中,或者在作为下面的布尔运算的操作数的时候,一个对象会被检查值是否为真。
默认情况下,一个对象,如果它的类定义了一个返回False的__bool__() 函数,或者是一个返回0的 __len__() 函数,那它就会被判定为假,其余情况下,他都是真。
None和False是假的- 任何数字类型的零是假的:
0,0.0,0j,Decimal(0),Fraction(0, 1) - 空的序列和集合是假的:
'',(),[],{},set(),range(0)
布尔运算:
| 运算 | 结果 |
|---|---|
x or y | 如果x为假,返回y,否则返回x |
x and y | 如果x为假,返回x,否则返回y |
not x | 如果x为假,返回True,否则返回False |
or、and、not这三个布尔运算符的优先级依次升高。not的优先级最高,a and b or not c 的评估顺序是这样的(a and b) or (not c),先评估not c、然后是(a and b),然后是整体。
x and y和x or y都有短路的作用,也就是说如果说从x已经能得到结果了,就不会再评估y。
比如x and y如果x的值为假,那么x and y一定为假,不用评估y就能得到结果了,直接返回x了,操作数y不会执行。
x or y,如果x为真,那么x or y就一定为真了,不用评估y就能得到结果,直接返回x,表达式y不会执行。
x = []
def y():
print('y')
return 1
a = x and y()
b = bool(x and y())
print(a, b) # [] False
二、比较
一共有8个比较运算,这8个比较运算的优先级是一样的,但是比较运算的优先级比布尔运算的优先级高。
| 运算 | 意义 |
|---|---|
< | 小于 |
<= | 小于或等于 |
> | 大于 |
>= | 大于或等于 |
== | 等于 |
!= | 不等于 |
is | 是 (对象标识) |
is not | 不是 (否定的对象标识) |
除了不同的数字类型外,所有其他不同的类型都认为是不等的。将不合适的类型进行比较时,会抛出TypeError。
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now + timedelta(days=-1)
print(now > yesterday) # True
print(2 <= 1.5) # False
print(2 <= now) # TypeError: '<=' not supported between instances of 'int' and 'datetime.datetime'
可以通过 __lt__(), __le__(), __gt__(), __ge__() , __eq__() 等函数自定义对象的比较行为。
x == y 只要x和y表示的值是一样的,就被认为是相等,但是is需要这x是同一个对象才行。对于类对象来说==和is是一样的。
e = [1, 2]
f = [1, 2]
print(e == f) # True
print(e is f) # False
print(id(e), id(f)) # 4479741616 4478061536
元组是不可变类型,下面例子中的c == d和c is d的结果都为True,并且打印出c、d的内存地址都一样,说明Python在背后做了一些优化,d和c的值是一样的,所以在定义d的时候,直接复用了已经创建好c的值,c和d指向了同一个对象。
c = (1, 2)
d = (1, 2)
print(c == d) # True
print(c is d) # True
print(id(c), id(d)) # 4470112416 4470112416
还有in 和 not in, x in s 被评估为 True 如果x是s的一个成员, 否则就是 False 。not in 是正好相反的。
print(1 in [1, 2, 3]) # True
print(1 not in (1, 2, 3)) # False
关于更细节的内容,可以查看:比较。
三、判断某个值的类型
isinstance(object, classinfo),如果object参数是classinfo参数的实例,或者classinfo参数的子类的实例,则isinstance(object, classinfo)返回True。
Python有以下这些内置的构造函数:
bool()、int()、float()、str()、list()、dict()、object()、range()、set()、slice()、tuple()、bytearray()、bytes()、complex()、frozenset()等。
g = 'g'
h = 1
i = [1, 2]
j = { 'j': 1 }
print(isinstance(g, str)) # True
print(isinstance(h, int)) # True
print(isinstance(i, list)) # True
print(isinstance(j, dict)) # True
- 使用type
type()返回对象的类型。在判断对象类型的时候推荐使用isinstance,因为它考虑到了子类。
print(type('g') == str) # True
print(type(1) == int) # True
四、计算
| 运算 | 结果 |
|---|---|
x + y | x 和 y 的和 |
x - y | x 和 y 的差 |
x * y | x 和 y 的乘积 |
x / y | x 和 y 的商 |
x // y | x 和 y 的商数 |
x % y | x / y 的余数 |
-x | x 取反 |
+x | x 不变 |
abs(x) | x 的绝对值或大小 |
int(x) | 将 x 转换为整数 |
float(x) | 将 x 转换为浮点数 |
pow(x, y) | x 的 y 次幂 |
x ** y | x 的 y 次幂 |
x / y的结果总是一个浮点数。x // y是x / y的商向下取整的数。
k = 2 / 1
print(k) # 2.0
l = 1 / 2
m = 1 // 2
print(l, m) # 0.5 0
n = 3.5 % 2
print(n) # 1.5
| 运算 | 结果 |
|---|---|
math.trunc(x) | 将x截断为整数 |
round(x[, n]) | 将x四舍五入为n位小数,一半的数值会舍入为偶数,如果省略n,则默认为0 |
math.floor(x) | Integral <= x,向下取整 |
math.ceil(x) | Integral >= x,向上取整 |
o = math.trunc(1.2)
p = round(1.2265, 2)
q = round(2.5)
r = math.floor(1.2)
s = math.ceil(1.2)
print(o, p, q, r, s) # 1 1.23 2 1 2
五、json和字符串转换
- json转字符串用
json.dumps() - 字符串转json用
json.loads()
import json
t = [
'a',
1,
{
'b': [1, 2, 3]
}
]
t_str = json.dumps(t)
t_json = json.loads(t_str)
print(t_str, t_json[2]['b'][0]) # '["a", 1, {"b": [1, 2, 3]}]' 1
六、list的相关方法
| 操作 | 结果 |
|---|---|
x in s | 如果s中有一项等于x,结果为True ,否则结果为False。 |
x not in s | 如果s中有一项等于x,结果为False ,否则结果为 True |
s + t | 拼接 s 和 t |
s * n 或者 n * s | 相当于n个s进行拼接 |
s[i] | s的第i项,i从0开始。 |
s[i:j] | s从i到j的切片 |
s[i:j:k] | s从i到j的切片,每个索引间隔k |
len(s) | s的长度 |
min(s) | s的最小的项 |
max(s) | s的最大的项 |
s.index(x[, i[, j]]) | 在s中出现的第一个x的索引位置(在索引i或者大于i,小于索引j的位置) |
s.count(x) | 在s中x出现的总次数 |
u = [1, 2]
v = [3, 4, 5, 6, 7, 8]
print(1 in u) # True
print(3 not in u) # True
print(u + v) # [1, 2, 3, 4, 5, 6, 7, 8]
print([None] * 2) # [None, None]
print(u[0]) # 1
print(v[1: 3]) # [4, 5]
print(v[0: 5: 1]) # [3, 4, 5, 6, 7]
print(len(u)) # 2
print(min(v)) # 3
print(max(v)) # 8
print(v.index(6)) # 3
print(v.count(1)) # 0
list相关,列表的方法:
list.append(x)
添加一项到列表的末尾。等同于a[len(a):] = [x]。
list.extend(iterable)
添加可迭代对象iterable中的所有项到list中。等同于a[len(a):] = iterable。
list.insert(i, x)
插入一项到给定的位置。将x插入索引为i的项前面。
list.remove(x)
移除列表中值为x的第一项。如果没有值为x的项,会抛出ValueError 。
list.pop([i])
移除列表中给定位置的项,并且返回它。如果没有声明索引i,就移除列表的最后一项并返回它。
list.clear()
移除列表中的所有项。等同于del a[:]。
d = [1, 2]
d.append(3)
print(d) # [1, 2, 3]
d.extend((3, 4, 5))
print(d) # [1, 2, 3, 3, 4, 5]
d.insert(0, 10)
print(d) # [10, 1, 2, 3, 3, 4, 5]
d.remove(3) # [10, 1, 2, 3, 4, 5]
print(d)
d.pop() # [10, 1, 2, 3, 4]
print(d)
d.clear() # []
print(d)
七、str的相关方法
str.find(sub[, start[, end]])
返回在字符串切片s[start:end]中出现的子字符串sub的第一个最低的索引位置。如果子字符串sub没有被找到,则返回-1。
w = 'abc'.find('a')
print(w) # 0
str.format(args, kwargs)
执行一个格式化字符串操作。str中可以包含文本字面量和 {},{}里面是位置参数的索引或者是关键字参数的名字。
x = '随便写点 {0}. {a}'.format('句子', a='哈哈')
print(x) # 随便写点 句子. 哈哈
str.join(iterable)
返回一个可迭代的对象中的值组成的字符。str是元素间的间隔。
y = ['基', '金', '狂', '跌', ',啧', '〠_〠']
print(''.join(y)) # 基金狂跌,啧〠_〠
str.split(sep=None, maxsplit=-1)
返回一个字符串中的单词组成的列表,使用sep作为分隔符。maxsplit 设置分隔的数量。如果没有声明maxsplit或者声明maxsplit的值为-1时,没有限制分隔的数量。
b = 'a, b, c, d, e'
print(b.split(',')) # ['a', ' b', ' c', ' d', ' e']
print(b.split(',', 2)) # ['a', ' b', ' c, d, e']
这个可以和str.join(iterable)对应使用。
str.lower()
返回一个字符转化为了小写字符的字符串。
z = 'Xyz'
print(z.lower()) # xyz
str.upper()
返回一个字符转化为了大写字符的字符串。
c = 'xyz'
print(c.upper()) # XYZ
str.replace(old, new[, count])
把字符串中出现的所有old字符串替换成新的字符串new,如果有count,就只替换前count个字符串。
a = '这个a字符串a里没a有英文字母a'
print(a.replace('a', '')) #这个字符串里没有英文字母
八、循环遍历支持迭代的对象
- 简单的遍历,使用
for in:
for e in ('a', 'b', 'c'):
print(e)
2.遍历序列时,使用enumerate,返回一个可迭代对象,通过它能同时拿到索引以及相应位置的值,这个方法等同于:
def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
例子:
for i, f in enumerate(['a', 'b', 'c']):
print(i, f)
# 0 a
# 1 b
# 2 c
3.遍历字典时,使用items()同时拿到字典的键和值。
g = {
'a': 10,
'b': 20,
'c': 30,
}
for k, v in g.items():
print(k, v)
# a 10
# b 20
# c 30
4.遍历两个或者多个对象,使用 zip()
h_arr = [1, 2, 3]
i_arr = [4, 5]
for h, i in zip(h_arr, i_arr):
print(h, i)
# 1 4
# 2 5
九、日期相关的方法
在《Python中几个日期相关的使用》中已记录。