Python 中让你相见恨晚的 20 个骚操做

2022年05月11日 阅读数：6

1.列表推导式

``````>>> [n*10 for n in range(5)]
[0, 10, 20, 30, 40]
``````

2.交换变量

``````>>> m, n = 1, 2
>>> m, n = n, m
>>> m
2
>>> n
1
``````

3.连续比较

``````>>> m, n = 3, 'c'
>>> 1 < m < 5
True
>>> 'd' < n < 'f'
False
``````

4.序列切片

``````>>> lst = [1, 2, 3, 4, 5]
>>> lst[:3]  # 取前三个数
[1, 2, 3]
>>> lst[::-1]  # 逆序
[5, 4, 3, 2, 1]
>>> lst[::2]  # 步长为2
[1, 3, 5]
>>> lst[::-2]  # 逆序步长为2
[5, 3, 1]
``````

5.切片快速增删序列

``````>>> lst = [1, 2, 3, 4, 5]
>>> lst[1:3] = []
>>> lst
[1, 4, 5]
>>> lst[1:3] = ['a', 'b', 'c', 'd']
>>> lst
[1, 'a', 'b', 'c', 'd']
``````

6.%timeit 计算运行时间

``````%timeit -n 10000 [n for n in range(5)]

# 2.41 µs ± 511 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
``````

7.三元表达式

``````>>> m = 4
>>> n = 2
>>> if m > n:
print('m')
else:
print('n')

m
>>> 'm' if m > n else 'n'
'm'
``````

``````>>> m = 4
>>> n = 2
>>> ("n", "m")[m > n]
'm'
``````

8.解包(unpack)

``````>>> a, b, *c = [1, 2, 3, 4]
>>> a
1
>>> b
2
>>> c
[3, 4]
>>> print(*range(3))
0 1 2
``````

9.lambda 匿名函数

`lambda` 函数能够接收任意多个参数 (包括可选参数) ，返回单个表达式值。 `lambda` 函数不能包含命令，只能包含一个表达式。

``````>>> def func(x, y):
return x * y

>>> func(2, 3)
6
>>> func = lambda x, y: x * y
>>> func(2, 3)
6
``````

10.map 序列映射

``````>>> def func(x):
return x ** 2

>>> list(map(func, [1,2,3]))
[1, 4, 9]
``````

``````>>> list(map(lambda x: x ** 2, [1, 2, 3]))
[1, 4, 9]
``````

11.filter 过滤序列

``````>>> def func(x):
return x % 3 == 0

>>> list(filter(func, [1, 2 ,3]))
[3]
``````

``````>>> list(filter(lambda x: x % 3 == 0, [1, 2, 3]))
[3]
``````

12.获取序列组合

``````>>> list1 = ['a', 'b']
>>> list2 = ['1', '2']
>>> [(m, n) for m in list1 for n in list2]
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]
>>> from itertools import product
>>> list(product(list1, list2))
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]
``````

13.随机选取序列元素

``````>>> from random import choice
>>> lst = [1, 2, 3, 4]
>>> choice(lst)
3
``````

``````>>> from random import choices
>>> lst = [1, 2, 3, 4]
>>> choices(lst, k=3)
[4, 3, 4]
``````

``````>>> from random import sample
>>> lst = [1, 2, 3, 4]
>>> sample(lst, k=3)
[4, 3, 2]
``````

14.序列元素计数

``````>>> from collections import Counter
>>> s = 'python+py'
>>> counter = Counter(s)
>>> counter
Counter({

'p': 2, 'y': 2, 't': 1, 'h': 1, 'o': 1, 'n': 1, '+': 1})
``````

``````>>> counter.keys()
dict_keys(['p', 'y', 't', 'h', 'o', 'n', '+'])
>>> counter.values()
dict_values([2, 2, 1, 1, 1, 1, 1])
>>> counter.items()
dict_items([('p', 2), ('y', 2), ('t', 1), ('h', 1), ('o', 1), ('n', 1), ('+', 1)])
``````

``````>>> counter.most_common(2)
[('p', 2), ('y', 2)]
``````

15.字典排序

``````>>> dic = {

'd': 2, 'c': 1, 'a': 3, 'b': 4}
>>> sort_by_key = sorted(dic.items(), key=lambda x: x[0], reverse=False)
>>> {

key: value for key, value in sort_by_key}
{

'a': 3, 'b': 4, 'c': 1, 'd': 2}
``````

``````>>> dic = {

'd': 2, 'c': 1, 'a': 3, 'b': 4}
>>> sort_by_value = sorted(dic.items(), key=lambda x: x[1], reverse=False)
>>> {

key: value for key, value in sort_by_value}
{

'c': 1, 'd': 2, 'a': 3, 'b': 4}
``````

16.字典合并

``````>>> dict1 = {

'name': '静香', 'age': 18}
>>> dict2 = {

'name': '静香', 'sex': 'female'}
``````
1. `update()` 更新字典。
``````>>> dict1.update(dict2)
>>> dict1
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````
1. 字典推导式
``````>>> {

k: v for dic in [dict1, dict2] for k, v in dic.items()}
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````
1. 元素拼接
``````>>> dict(list(dict1.items()) + list(dict2.items()))
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````
1. `chain()` 能够将序列链接，返回可迭代对象。
``````from itertools import chain
>>> dict(chain(dict1.items(), dict2.items()))
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````
1. `collections.ChainMap` 能够将多个字典或映射，并将它们合并。
``````>>> from collections import ChainMap
>>> dict(ChainMap(dict2, dict1))
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````
1. `Python3.5` 以上的版本中，能够经过字典解包进行合并。
``````>>> {

**dict1, **dict2}
{

'name': '静香', 'age': 18, 'sex': 'female'}
``````

17.zip 打包

`zip()` 将序列中对应的元素打包成一个个的元组，而后返回由这些元组组成的迭代器。

``````>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> list3 = ['a', 'b', 'c', 'd']
>>> res = zip(list1, list2)
>>> res
<zip object at 0x0000013C13F62200>
>>> list(res)
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(list2, list3))
[(4, 'a'), (5, 'b'), (6, 'c')]
``````

18.enumerate 遍历

`enumerate` 函数能够将可迭代对象组合成一个索引序列，这样遍历时就能够同时获取索引与对应的值。

``````>>> lst = ['a', 'b', 'c']
>>> for index, char in enumerate(lst):
print(index, char)

0 a
1 b
2 c
``````

19.any() & all()

`any(iterable)`

• 对于迭代过程当中的元素 i，只有全部元素 bool(i) 的结果都为 False，`any` 的结果才返回 False。
• 若是迭代是空，返回 False。

`all(iterable)`

• 对于迭代过程当中的元素 i，若是存在一个 bool(i) 的结果为 False，则 `all` 结果返回 False。
• 若是可迭代对象为空，则返回 True。
``````>>> any('')
False
>>> any([])
False
>>> any([1, 0, ''])
True
>>> any([0, '', []])
False
>>> all([])
True
>>> all([1, 0, ''])
False
>>> all([1, 2, 3])
True
``````

20.用 ** 代替 pow

``````%timeit -n 10000 c = pow(2,10)
# 911 ns ± 107 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit -n 10000 c = 2 ** 10
# 131 ns ± 46.8 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
``````

👇🏻 关注小卡片，回复“交流群”，一块儿学习Python👇🏻