接着昨天的分享写,昨天的链接为:Python编程特殊小技巧汇集(一)
21、列表切片,
a = [1,2,3,'domi','mi']
>>> a[2:4] # 提取第3个位置到第5个位置(不包含第5个位置)的数据
[3, 'domi']
>>> a[:3] # 提取前3个数据
[1, 2, 3]
>>> a[::2] # 提取偶数项
[1, 3, 'mi']
>>> a[1::2] # 提取奇数项
[2, 'domi']
>>> a[::-1] # 列表反转
['mi', 'domi', 3, 2, 1]
22、二维数组转为一维数组
import itertools
a = [[1,2],[3,4],[5,6]]
b = itertools.chain(*a)
>>> list(b)
[1, 2, 3, 4, 5, 6]
23、带索引的迭代
a = ['d','o','m','i']
for index, value in enumerate(a):
print('第%d个数据为%s' %(index, value))
第0个数据为d
第1个数据为o
第2个数据为m
第3个数据为i
24、列表推导式
a = [x*3 for x in range(3)]
>>> a
[0, 3, 6]
a = [x*3 for x in range(10) if x%2 == 0]
>>> a
[0, 6, 12, 18, 24]
25、生成器表达式
ge = (x*2 for x in range(10))
>>> ge
<generator object <genexpr> at 0x000001372D39F270>
>>> next(ge)
0
>>>
>>> next(ge)
2
>>> next(ge)
4
>>> next(ge)
6
>>> next(ge)
8
>>> next(ge)
10
>>> next(ge)
12
>>> next(ge)
14
>>> next(ge)
16
>>> next(ge)
18
>>> next(ge) # 迭代结束
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
26、集合推导式
>>> nums = {n**2 for n in range(10)}
>>> nums
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
27、判断key是否存在字典中判断key是否存在字典中
>>> d = {"1":"a"}
>>> d['2']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '2'
>>> d['1']
'a'
>>> '1' in d
True
>>> '2' in d
False
>>> d.get('1')
'a'
>>> d.get('2')
28、打开文件
with open('foo.txt', 'w') as f:
f.write("hello world")
29、两个列表组合成字典
a = ["One","Two","Three"]
b = [1,2,3]
dictionary = dict(zip(a, b))
print(dictionary)
30、去除列表中重复元素
my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
31、打印日历
import calendar
>>> print(calendar.month(2021, 1))
January 2021
Mo Tu We Th Fr Sa Su
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、匿名函数
def add(a, b):
return a+b
# 等同于
add = lambda a,b:a+b
add(1,2)