Python六剑客

1、切片

切片:截取可迭代对象的部分内容(list,tuple,dict,set,str)

2、列表解析式

列表解析式可以快速的生成一个列表

不带if条件的:

格式:[expression for i in Iterable]

>>> l = [x for x in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

带if条件的:

>>> l = [x for x in range(10) if x%2==0]
>>> l
[0, 2, 4, 6, 8]

二维列表生成:

>>> ll=[[i for i in range(10)] for j in range(10)]
>>> ll
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> for i in ll:
... print(i)
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

3、map

映射(map):对可迭代对象中的每个元素执行指定的函数,第一个参数是函数名,第二个参数是Iterable(可迭代对象),返回的map属于Iterator

>>> def pow_l(x):
... return x**2
...
>>> a=map(pow_l,range(1,10))
>>> print("a 的类型:%s" %type(a))#查看类型
a 的类型:<class 'map'>
>>> from collections import Iterator
>>> from collections import Iterable
>>> print("a 是Iterator:%s" %isinstance(a,Iterator))#查看是否是Iterator
a 是Iterator:True
>>> print("a 是Iterable:%s" %isinstance(a,Iterable))#查看是否是Iterable
a 是Iterable:True
>>> for i in a:#a作为Iterable使用
... print(i,end=' ')
...
1 4 9 16 25 36 49 64 81

4、reduce

归纳函数(reduce):第一个参数是函数名,第二个参数是sequence(序列,像list,tuple,str,set,dict都可以)

效果:reduce(f,[x1,x2,x3,x4])    =    f(f(f(x1,x2),x3),x4)

>>> from functools import reduce
>>> def add_l(x,y):
... return x+y
...
>>> r_l=reduce(add_l,range(1,10))
>>> print(r_l)
45

>>> print("r_l 的类型:%s" %type(r_l))
r_l 的类型:<class 'int'>

5、filter

过滤器(filter)第一个参数是函数名,用于筛选的函数,第二个参数是Iterable(list,tuple,set,dict,str),返回一个filter且filter属于Iterator

用于过滤掉一切不需要的东西

 6、lambda

只有一行的函数

正经函数:

>>> def square_l(x):
... return x*x
...
>>> square_l(2)
4

lambda:

>>> squarel=lambda x:x*x#冒号后面的一切都是对输入的操作,然后lambda x会返回结果

>>> squarel(2)
4

#配合map,filter等lambda能发挥更大作用

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

>>> list(filter(lambda x:x<4,[1,2,3,4,5]))
[1, 2, 3]

原文地址:https://www.cnblogs.com/suitcases/p/12109195.html