Python - 内置函数 选例

概览参见  https://www.runoob.com/python/python-built-in-functions.html

官方文档  https://docs.python.org/3/library/functions.html?highlight=built#ascii 

0. 高阶函数

  满足俩个特性任意一个即为高阶函数

  1.函数的传入参数是一个函数名

  2.函数的返回值是一个函数名

1. map() 函数

  map(functioniterable...) 即接收两种参数,函数 f 和 可迭代对象, map将传入的函数依次作用到序列的每个元素,返回的为迭代对象map类型。

  用法举例:

num1 = [1, 2, 4, 7, 11]


# lambda x: x+1
def add(x):
    return x+1


# lambda x: x**2
def pf(x):
    return x**2


def map_test(func, array):
    num2 = []
    for i in array:
        res = func(i)
        num2.append(res)
    return num2

ret = map_test(lambda x: x+1, num1)
print(ret)

rett = map_test(lambda x: x**2, num1)
print(rett)


rettt = map(lambda x:x+1, num1)
# 第一个参数为可用匿名函数或者有名函数,第二个参数为可迭代对象,返回值为可迭代对象
print(rettt)
retttt = list(rettt)
print(retttt)


name = "helloworld"
s = list(map(lambda x:x.upper(), name))
print(s)

===============
[2, 3, 5, 8, 12]
[1, 4, 16, 49, 121]
<map object at 0x00000000022FAAC8>
[2, 3, 5, 8, 12]
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

2. filter() 函数

  filter(functioniterable) filter()函数接收一个函数 f 和一个可迭代对象,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新的可迭代对象。

  用法举例:

people = ['m_zhangsan_sb', 'lisi', 'm_wangwu_sb', 'chenliu']

# lambda x:x.endswith('sb')
def end(n):
    return n.endswith('sb')

def filter_test(func, array):
    ret = []
    for i in array:
        if func(i):
            ret.append(i)
    return ret

a = filter_test(lambda x:x.endswith('sb'), people)
print(a)
l = list(filter(lambda x: x.endswith('sb'), people))
print(l)

===============
['m_zhangsan_sb', 'm_wangwu_sb']
['m_zhangsan_sb', 'm_wangwu_sb']

3. reduce() 函数

  reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

  

例如,编写一个f函数,接收x和y,返回x和y的和:

1
2
def f(x, y):
    return + y

调用 reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:

1
2
3
4
5
先计算头两个元素:f(13),结果为4
再把结果和第3个元素计算:f(45),结果为9
再把结果和第4个元素计算:f(97),结果为16
再把结果和第5个元素计算:f(169),结果为25
由于没有更多的元素了,计算结束,返回结果25

上述计算实际上是对 list 的所有元素求和。虽然Python内置了求和函数sum(),但是,利用reduce()求和也很简单。

reduce()还可以接收第3个可选参数,作为计算的初始值。如果把初始值设为100,计算:

1
reduce(f, [13579], 100)

结果将变为125,因为第一轮计算是:

计算初始值和第一个元素:f(100, 1),结果为101

  用法举例:

num1 = [1,2,3,4]

def reduce_test(func, array, init=None):
    if init == None:
        res = array.pop(0)
    else:
        res = init
    for i in array:
        res = func(res, i)
    return res

a = reduce_test(lambda x,y:x*y, num1)
print(a)

# 先导入库
from functools import reduce
b = reduce(lambda x,y:x*y, num1, 100)
print(b)

============
24
2400

 

4. zip() 函数

  zip(*iterables)

  

zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。具体意思不好用文字来表述,直接看示例:

1.示例1:

复制代码
x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

print xyz
复制代码

运行的结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

从这个结果可以看出zip函数的基本运作方式。

2.示例2:

x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy

运行的结果是:

[(1, 4), (2, 5), (3, 6)]

从这个结果可以看出zip函数的长度处理方式。

3.示例3:

x = [1, 2, 3]
x = zip(x)
print x

运行的结果是:

[(1,), (2,), (3,)]

从这个结果可以看出zip函数在只有一个参数时运作的方式。

4.示例4:

x = zip()
print x

运行的结果是:

[]

从这个结果可以看出zip函数在没有参数时运作的方式。

5.示例5:

复制代码
x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

u = zip(*xyz)

print u
复制代码

运行的结果是:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

一般认为这是一个unzip的过程,它的运行机制是这样的:

在运行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

那么,zip(*xyz) 等价于 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))

所以,运行结果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

注:在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数)

6.示例6:

x = [1, 2, 3]
r = zip(* [x] * 3)
print r

运行的结果是:

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

它的运行机制是这样的:

[x]生成一个列表的列表,它只有一个元素x

[x] * 3生成一个列表的列表,它有3个元素,[x, x, x]

zip(* [x] * 3)的意思就明确了,zip(x, x, x)

 

5. max() min() 函数 (跟sort()可类比)

max(iterable, key, default) 求迭代器的最大值,其中iterable 为迭代器,max会for i in … 遍历一遍这个迭代器,然后将迭代器的每一个返回值当做参数传给key=func 中的func(一般用lambda表达式定义) ,然后将func的执行结果传给key,然后以key为标准进行大小的判断。

以下根据不同的判断条件返回最大值也不同

d1 = {'name': 'egon', 'price': 100}
d2 = {'name': 'rdw', 'price': 666}
d3 = {'name': 'zat', 'price': 1}
l1 = [d1, d2, d3]
a = max(l1, key=lambda x: x['name'])
print(a)
b = max(l1, key=lambda x: x['price'])
print(b)

===================
{'name': 'zat', 'price': 1}
{'name': 'rdw', 'price': 666}
people = [
    {'name': 'zs', 'age': 1},
    {'name': 'ls', 'age': 2},
    {'name': 'ww', 'age': 6},
    {'name': 'cl', 'age': 4}
]

a = max(people, key=lambda dic:dic['age'])
print(a)

=================
{'name': 'ww', 'age': 6}

  

  

posted @ 2017-08-05 17:56  云中王  阅读(293)  评论(0编辑  收藏  举报