一些Python中常用的基础方法

499 阅读6分钟

一、判断某值是否为真

真值检测

当在 if 或者 while 语句中,或者在作为下面的布尔运算的操作数的时候,一个对象会被检查值是否为真。

默认情况下,一个对象,如果它的类定义了一个返回False__bool__() 函数,或者是一个返回0的 __len__() 函数,那它就会被判定为假,其余情况下,他都是真。

  • NoneFalse是假的
  • 任何数字类型的零是假的: 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

orandnot这三个布尔运算符的优先级依次升高。not的优先级最高,a and b or not c 的评估顺序是这样的(a and b) or (not c),先评估not c、然后是(a and b),然后是整体。

x and yx 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 只要xy表示的值是一样的,就被认为是相等,但是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 == dc is d的结果都为True,并且打印出cd的内存地址都一样,说明Python在背后做了一些优化,dc的值是一样的,所以在定义d的时候,直接复用了已经创建好c的值,cd指向了同一个对象。

c = (1, 2)
d = (1, 2)

print(c == d) # True
print(c is d) # True
print(id(c), id(d)) # 4470112416 4470112416

还有innot inx in s 被评估为 True 如果xs的一个成员, 否则就是 Falsenot in 是正好相反的。

print(1 in [1, 2, 3]) # True
print(1 not in (1, 2, 3)) # False

关于更细节的内容,可以查看:比较

三、判断某个值的类型

  1. 使用isinstance

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
  1. 使用type

type()返回对象的类型。在判断对象类型的时候推荐使用isinstance,因为它考虑到了子类。

print(type('g') == str) # True
print(type(1) == int) # True

四、计算

数字类型

运算结果
x + yxy 的和
x - yxy 的差
x * yxy 的乘积
x / yxy 的商
x // yxy 的商数
x % yx / y 的余数
-xx 取反
+xx 不变
abs(x)x 的绝对值或大小
int(x)x 转换为整数
float(x)x 转换为浮点数
pow(x, y)xy 次幂
x ** yxy 次幂

x / y的结果总是一个浮点数。x // yx / 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

  1. json转字符串用json.dumps()
  2. 字符串转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拼接 st
s * n 或者 n * s相当于ns进行拼接
s[i]s的第i项,i0开始。
s[i:j]sij的切片
s[i:j:k]sij的切片,每个索引间隔k
len(s)s的长度
min(s)s的最小的项
max(s)s的最大的项
s.index(x[, i[, j]])s中出现的第一个x的索引位置(在索引i或者大于i,小于索引j的位置)
s.count(x)sx出现的总次数
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相关,列表的方法:

  1. list.append(x)

添加一项到列表的末尾。等同于a[len(a):] = [x]

  1. list.extend(iterable)

添加可迭代对象iterable中的所有项到list中。等同于a[len(a):] = iterable

  1. list.insert(i, x)

插入一项到给定的位置。将x插入索引为i的项前面。

  1. list.remove(x)

移除列表中值为x的第一项。如果没有值为x的项,会抛出ValueError

  1. list.pop([i])

移除列表中给定位置的项,并且返回它。如果没有声明索引i,就移除列表的最后一项并返回它。

  1. 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

  1. str.find(sub[, start[, end]])

返回在字符串切片s[start:end]中出现的子字符串sub的第一个最低的索引位置。如果子字符串sub没有被找到,则返回-1

w = 'abc'.find('a')
print(w) # 0
  1. str.format(args, kwargs)

执行一个格式化字符串操作。str中可以包含文本字面量和 {}{}里面是位置参数的索引或者是关键字参数的名字。

x = '随便写点 {0}. {a}'.format('句子', a='哈哈')
print(x) # 随便写点 句子. 哈哈
  1. str.join(iterable)

返回一个可迭代的对象中的值组成的字符。str是元素间的间隔。

y = ['基', '金', '狂', '跌', ',啧', '〠_〠']
print(''.join(y)) # 基金狂跌,啧〠_〠
  1. 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)对应使用。

  1. str.lower()

返回一个字符转化为了小写字符的字符串。

z = 'Xyz'
print(z.lower()) # xyz
  1. str.upper()

返回一个字符转化为了大写字符的字符串。

c = 'xyz'
print(c.upper()) # XYZ
  1. str.replace(old, new[, count])

把字符串中出现的所有old字符串替换成新的字符串new,如果有count,就只替换前count个字符串。

a = '这个a字符串a里没a有英文字母a'
print(a.replace('a', '')) #这个字符串里没有英文字母

八、循环遍历支持迭代的对象

循环

  1. 简单的遍历,使用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中几个日期相关的使用》中已记录。