Python基础之内置特定函数

1.map

 map(处理逻辑,可遍历的对象)   处理序列中的每个元素,元素个数及位置与原来一样

配和lambda使用节省代码量,但是lambda只能处理简单的逻辑

v = "AL"        
print(list(map(lambda x: x.lower(), v)))   
# 结果为 ['a', 'l']

我觉得实现机制可能

a = []
def jianer(array):
    for i in array:
        a.append(i.lower())
    print(a)
jianer(v)
 
结果
['a', 'l']

2.filter:

filter(处理逻辑,可遍历对象) 遍历序列中的每个元素,判断每个元素的布尔值为True则保留元素

返回值 为一个列表,把找到的结果存到列表中

movie_people['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
print(list(filter(lambdan:n.endswith('sb'),movie_people)))   
movie_people = ['alex_sb''wupeiqi_sb''linhaifeng''yuanhao_sb']
def filter_test(array):
    ret = []
    for in array:
        if not i.endswith('sb'):
            ret.append(i)
    return ret
res = filter_test(movie_people)

3.reduce

  reduce(函数,序列,默认空参数) 处理一个序列,然后把序列进行合并操作

  必须导入from funtools import reduce

 

from functools import reduce          # reduce 用reduce函数要定义这句话
 
num_l = [1, 2, 3, 100]
print(reduce(lambda x, y: x + y, num_l, 1))
print(reduce(lambda x, y: x + y, num_l))
1 num_l = [1, 2, 3, 100]
 2 res = 0
 3 for num in num_l:
 4     res += num
 5 print(res)
 6 
 7 
 8 def reduce_test(array):
 9     res = 0
10     for num in array:
11         res += num
12     return res
13 
14 ret = reduce_test(num_l)
15 print(ret)
16 
17 结果都为106

4.zip

例1:
l1=[1,2,3] l2=['a','b'] print(list(zip(l1,l2))) >>>>[(1, 'a'), (2, 'b')] # 输出时一一对应 对应不上的就舍弃
例2:
for (x,y)in zip(l1,l2):
  print(x,y)
# 实现并行运行

  1.在python2版本中map函数

#较旧的版本中,map用和zip类似的方法元素配对,如果长度不同,一较短的序列用None补齐
s=[1,2]
s1=['a','b','c']
map(None,s,s1)
>>>>>>[(1,'a'),(2,'b')]

 2.map\zip \filter迭代器

   python3.0中(range\map\zip\filter)等内置函数转变陈迭代器,节约了内存空间。但是缺点迭代器在遍历结果后,就没办法在进行遍历

    

例1:
m=map(abs,(-1,2,3))
print(m.__next__())
print(m.__next__())
print(m.__next__())
>>>>>1
>>>>>2
>>>>>3

 

 

    

posted @ 2017-05-29 17:08  红领巾下的大刀疤  阅读(125)  评论(0编辑  收藏  举报
/* 看板娘 */