python-useful-skills

本文最后更新于:2023年6月19日 晚上

一些好用的 python 内置属性、函数、技巧。

内置函数

Built-in Functions
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() [eval()](https://docs.python.org/3/library/functions.html#eval)--执行字符串命令 int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()

字符串操作

字符串常量

string.ascii_letters

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

string.ascii_lowercase

abcdefghijklmnopqrstuvwxyz

string.digits

0123456789

string.punctuation

!”#$%&’()*+,-./:;<=>?@[]^_`{|}~

string.whitespace

\t\n\r\x0b\x0c

格式化字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

#按名称访问参数:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

#对齐文本以及指定宽度:
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
####################
>>> width = 5
>>> for num in range(5,12):
... for base in 'dXob':
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
10 A 12 1010
11 B 13 1011

内置函数

  1. str.encode(encoding="utf-8", errors="strict")
  2. str.find(sub[, start[, end]])

返回子字符串  sub  在  s[start:end]  切片内被找到的最小索引。 可选参数  start  与  end  会被解读为切片表示法。 如果  sub  未被找到则返回  -1

  1. str.isalnum``()

如果字符串中的所有字符都是字母或数字且至少有一个字符,则返回  True , 否则返回  False 。 如果  c.isalpha() , c.isdecimal() , c.isdigit() ,或  c.isnumeric()  之中有一个返回  True ,则字符c是字母或数字。

  1. str.isalpha()

如果字符串中的所有字符都是字母,并且至少有一个字符,返回 True ,否则返回 False 。字母字符是指那些在 Unicode 字符数据库中定义为 “Letter” 的字符,即那些具有 “Lm”、”Lt”、”Lu”、”Ll” 或 “Lo” 之一的通用类别属性的字符。 注意,这与 Unicode 标准中定义的”字母”属性不同。

  1. str.isascii()

如果字符串为空或字符串中的所有字符都是 ASCII ,返回 True ,否则返回 False 。ASCII 字符的码点范围是 U+0000-U+007F 。
_

  1. str.isdecimal()

如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符,则返回 True , 否则返回 False 。十进制字符指那些可以用来组成 10 进制数字的字符,例如 U+0660 ,即阿拉伯字母数字 0 。 严格地讲,十进制字符是 Unicode 通用类别 “Nd” 中的一个字符。

  1. str.isdigit()

如果字符串中的所有字符都是数字,并且至少有一个字符,返回 True ,否则返回 False 。 数字包括十进制字符和需要特殊处理的数字,如兼容性上标数字。这包括了不能用来组成 10 进制数的数字,如 Kharosthi 数。 严格地讲,数字是指属性值为 Numeric_Type=Digit 或 Numeric_Type=Decimal 的字符。

  1. str.isspace()

如果字符串中只有空白字符且至少有一个字符则返回 True ,否则返回 False

  1. str.join(iterable)

返回一个由 iterable 中的字符串拼接而成的字符串。 如果 iterable 中存在任何非字符串值包括 bytes 对象则会引发 TypeError。 调用该方法的字符串将作为元素之间的分隔。

  1. str.replace(old, new[, count])

返回字符串的副本,其中出现的所有子字符串 old 都将被替换为 new_。 如果给出了可选参数 _count_,则只替换前 _count 次出现。

  1. str.rsplit(sep=None, maxsplit=-1)

返回一个由字符串内单词组成的列表,使用 sep 作为分隔字符串。 如果给出了 maxsplit_,则最多进行 _maxsplit 次拆分,从 最右边 开始。 如果 sep 未指定或为 None,任何空白字符串都会被作为分隔符。 除了从右边开始拆分,rsplit() 的其他行为都类似于下文所述的 split()

  1. str.translate(table)

返回原字符串的副本,其中每个字符按给定的转换表进行映射。 转换表必须是一个使用 __getitem__() 来实现索引操作的对象,通常为 mappingsequence。 当以 Unicode 码位序号(整数)为索引时,转换表对象可以做以下任何一种操作:返回 Unicode 序号或字符串,将字符映射为一个或多个字符;返回 None,将字符从结果字符串中删除;或引发 LookupError 异常,将字符映射为其自身。
你可以使用 str.maketrans() 基于不同格式的字符到字符映射来创建一个转换映射表。

密码学

hashlib 模块

可用的哈希算法构造器有  sha1(), sha224()sha256()sha384()sha512()blake2b()和  blake2s()md5()通常也是可用的。
具体清单如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{'blake2b',
'blake2s',
'md5',
'sha1',
'sha224',
'sha256',
'sha384',
'sha3_224',
'sha3_256',
'sha3_384',
'sha3_512',
'sha512',
'shake_128',
'shake_256'}

用法示例:

1
2
3
4
5
hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
#'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

In []: hashlib.md5(b'1111').hexdigest()
Out[]: 'b59c67bf196a4758191e42f76670ceba'

详细用法可参考:https://docs.python.org/zh-cn/3/library/hashlib.html

二进制操作

操作二进制数据的核心内置类型是  bytes  和  bytearray
bytes 对象是由整数构成的序列(类似于元组),但其实操作仍然类似于字符串,上面提到的函数在 byte 中仍然适用。
bytearray 对象是可变的,该对象除了  bytes 和 bytearray 操作  中所描述的 bytes 和 bytearray 共有操作之外,还支持  可变  序列操作。

内存视图

memoryview  对象允许 Python 代码访问一个对象的内部数据

创建一个引用  obj  的  memoryview。 obj  必须支持缓冲区协议。 支持缓冲区协议的内置对象包括  bytes  和  [bytearray](https://docs.python.org/zh-cn/3/library/stdtypes.html#bytearray)array

memoryview  具有  元素  的概念,即由原始对象  obj  所处理的基本内存单元。 对于许多简单类型例如  bytes  和  bytearray  来说,一个元素就是一个字节,但是其他的类型例如  array.array  可能有更大的元素。

1
2
3
4
5
>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> bytes(v[1:4])
b'bce'

set 集合

set  对象是由具有唯一性的  hashable  对象所组成的无序多项集。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算,例如交集、并集、差集与对称差集等等。

作为一种无序的多项集,集合并不记录元素位置或插入顺序。 相应地,集合不支持索引、切片或其他序列类的操作

set  类型是可变的 — 其内容可以使用  add()  和  remove()  这样的方法来改变。 由于是可变类型,它没有哈希值,且不能被用作字典的键或其他集合的元素。 
集合可用多种方式来创建:

  • 使用花括号内以逗号分隔元素的方式: {'jack', 'sjoerd'}

  • 使用集合推导式: {c for c in 'abracadabra' if c not in 'abc'}

  • 使用类型构造器: set(), set('foobar'), set(['a', 'b', 'foo'])

  • isdisjoint(other)

如果集合中没有与 other 共有的元素则返回 True。 当且仅当两个集合的交集为空集合时,两者为不相交集合。

  • issubset(other)set <= other

检测是否集合中的每个元素都在 other 之中。

  • set < other

检测集合是否为 other 的真子集,即 set <= other and set != other

  • issuperset(other)set >= other

检测是否 other 中的每个元素都在集合之中。

  • set > other

检测集合是否为 other 的真超集,即 set >= other and set != other

  • intersection(*others)

set & other & ...
返回一个新集合,其中包含原集合以及 others 指定的所有集合中共有的元素。

  • difference(*others)set - other - ...

返回一个新集合,其中包含原集合中在 others 指定的其他集合中不存在的元素。

  • symmetric_difference(other)set ^ other

返回一个新集合,其中的元素或属于原集合或属于 other 指定的其他集合,但不能同时属于两者。

  • update(*others)set |= other | ...

更新集合,添加来自 others 中的所有元素。

  • intersection_update(*others)set &= other & ...

更新集合,只保留其中在所有 others 中也存在的元素。

  • difference_update(*others)set -= other | ...

更新集合,移除其中也存在于 others 中的元素。

  • symmetric_difference_update(other)set ^= other

更新集合,只保留存在于集合的一方而非共同存在的元素。

  • add(elem)

将元素 elem 添加到集合中。

  • remove(elem)

从集合中移除元素 elem_。 如果 _elem 不存在于集合中则会引发 KeyError

  • discard(elem)

如果元素 elem 存在于集合中则将其移除。

  • pop()

从集合中移除并返回任意一个元素。 如果集合为空则会引发 KeyError

字典 dict

字典取值常常直接 d[j]了,但是有可能报错,这里有一种更保险的取值方式–
get(key[, default])
如果 key 存在于字典中则返回 key 的值,否则返回 default_。 如果 _default 未给出则默认为 None,因而此方法绝不会引发 KeyError

其他操作:

  • reversed(d)

返回一个逆序获取字典键的迭代器。 这是 reversed(d.keys()) 的快捷方式。

  • setdefault(key[, default])

如果字典存在键 key ,返回它的值。如果不存在,插入值为 default 的键 key ,并返回 defaultdefault 默认为 None

  • values()

返回由字典值组成的一个新视图。

  • keys()

返回由字典键组成的一个新视图。

iter(dictview)
返回字典中的键、值或项(以 (键, 值) 为元素的元组表示)的迭代器。
键和值是按插入时的顺序进行迭代的。 这样就允许使用 zip() 来创建 (值, 键) 对: pairs = zip(d.values(), d.keys())。 另一个创建相同列表的方式是 pairs = [(v, k) for (k, v) in d.items()].

tuple-元组

元组是:

  • 不可变
  • 有序
  • 异质
  • 索引(从零开始)
  • 带圆括号(可选,但建议)
  • 在迭代过程中更快,因为它是不可变的

元组对于创建通常包含相关信息(例如员工信息)的对象很有用。换句话说,元组可以让我们将相关信息“块”在一起,并将其用作单个事物。

访问元素

  • 正索引从元组的开始开始计数。
  • 负索引从元组的末尾开始计数。
  • 一定范围的索引将使用指定的项目创建一个新的元组(称为Slicing)。
  • 范围[m:n]是指从位置 m(_含_)到位置 n(_不含_)。
  • 使用双索引访问嵌套元组的元素。

创建键值对(命名)元组

命名元组示例

1
2
3
4
5
6
7
import collections
Record = collections.namedtuple('Record', ['id', 'name', 'date'])
R1 = Record('1', 'My Record', '12/12/2020')
#Accessing using index
print("Record id is:", R1[0]) # Record id is: 1
# Accessing using key
print("Record name is:", R1.name) # Record name is: My Record

不过创建之后无法改变它们的值了,因为是元组。

属性判断

不要在 if 中使用 type 函数判断属性,而应该选择 isinstance()函数,例如:

1
2
>> isinstance('11',str)
True

map-作用于 list 每一个元素

参考:https://yangfangs.github.io/2017/08/23/python-map-zip-filter-reduce/

map()是 Python 内置的高阶函数,它接收一个函数 f() 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

  1. 例如 chr 类型转换成 int
1
2
3
l = ['1','2','3','4']
list(map(int,l))
Out[2]: [1, 2, 3, 4]
  1. 编写独立函数作用与 list 中每一个元素:
    • 例如对 list 中每一个元素求平方
1
2
3
4
5
def f(x):
return x**2
l =[1,2,3,4]
list(map(f,l))
Out[3]: [1, 4, 9, 16]
  1. 使用匿名函数操作:
1
2
3
l =[1,2,3,4]
list(map(lambda x: x**2, l))
Out[4]: [1, 4, 9, 16]

同时操作两个 list(并行非多核运算)

1
2
3
l =[1,2,3,4]
list(map(lambda x,y: x+y,l,l))
Out[5]: [2, 4, 6, 8]

注:python3 和 python2 中 map()的返回值不一样, python2 中直接返回列表,python 需要加 list()转换取值。

filter-筛选函数

按照 function 函数的规则在列表 sequence 中筛选数据

  • 用法:filter(function, sequence)

筛选 list 中符合条件的值

1
2
3
l =[1,2,3,4]
filter(lambda x: x>2, l)
Out[6]: [3, 4]

filter() 与 map() 返回值不同

1
2
3
l =[1,2,3,4]
map(lambda x: x>2, l)
Out[8]: [False, False, True, True]

reduce()——求积累运算

reduce 函数功能是将 sequence 中数据,按照 function 函数操作,如将列表第一个数与第二个数进行 function 操作,得到的结果和列表中下一个数据进行 function 操作,一直循环下去…

  • 用法 reduce(function, sequence):

求积累和

1
2
3
l =[1, 2, 3, 4]
reduce(lambda x,y: x+y, l)
Out[10]: 10

zip()打包函数

  • zip()是 Python 的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个 tuple(元组),然后返回由这些 tuples 组成的 list(列表)。若传入参数的长度不等,则返回 list 的长度和参数中长度最短的对象相同。利用*号操作符,可以将 list unzip(解压)。

  • 用法: zip(list,list)

zip()基本用法

1
2
3
4
l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
zip(l1,l2)
Out[12]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]

使用*逆过程

1
2
3
4
5
l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
zip_l1_l2 = zip(l1,l2)
zip(*zip_l1_l2)
Out[17]: [(1, 2, 3, 4), ('a', 'b', 'c', 'd')]

zip 构造字典

1
2
3
4
5
l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
zip_l1_l2 = zip(l1,l2)
dict(zip_l1_l2)
Out[18]: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

这个操作就可以更加优雅的创造数据结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
In [63]: a = collections.namedtuple('stu',['id','name','sex'])

In [64]: a
Out[64]: __main__.stu

In [65]: s1 = a(1,'11','f')

In [66]: s1
Out[66]: stu(id=1, name='11', sex='f')

In [67]: l1
Out[67]: [1, 2, 3, 4]

In [68]: l2 = [s1,s1,s1,s1]

In [69]: ll = zip(l1,l2)

In [70]: f = dict(ll)

In [71]: f
Out[71]:
{1: stu(id=1, name='11', sex='f'),
2: stu(id=1, name='11', sex='f'),
3: stu(id=1, name='11', sex='f'),
4: stu(id=1, name='11', sex='f')}

In [72]: f[1]
Out[72]: stu(id=1, name='11', sex='f')

In [73]: f[1].id
Out[73]: 1

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!