python学习笔记------高阶函数

高阶函数

高阶函数:实参可以是一个函数;返回值可以使一个函数;

内置高阶函数
map函数

# 1. map函数理解

from collections import Iterable
def func(x):
    return x**2

f = map(func, [0,1,2,3,4])

for i in f:
    print(i)

print(isinstance(f, Iterable))


# 1. map函数练习
# 需求: 用户接收一串数字; '1 3 5 7 8', 将该字符串中的所有数字转化为整形,并以列表格式输出;
s = '1 3 5 7 8'
a, b, c, d, e = list(map(int, s.split()))
print(a,e)

print([int(i) for i in s.split()])     # list

0
1
4
9
16
True
1 8
[1, 3, 5, 7, 8]
reduce函数

# reduce: python2.x有, python3.x取消
# reduce在python3.x不是内置高阶函数, 而是需要导入from functools import reduce;

# In [2]: def add(x,y):
#    ...:     return x+y
#    ...:
#
# In [3]: reduce(add, [1,2,3,4,5,6])
# Out[3]: 21
#
# In [4]: (((1+2)+3)+4)


from functools import reduce
def add(x,y):
    return x+y
print(reduce(add, range(5)))


# 需求: 用户输入数字n; 求n的阶乘;  5!= 1*2*3*4*5

def func(x,y):
    return x*y
print(reduce(func, range(1,6)))   # func(func(1,2),3)

10
120
filter高阶函数

# filter高阶函数: filter(func, iterable)
#  1. func: 只有一个形参, 函数的返回值只能是True或者False;

def isodd(num):
    if num %2 == 0:
        return True
    else:
        return False
print(list(filter(isodd, range(10))))


###[0, 2, 4, 6, 8]
sorted函数

# sorted:
# 排序: 由大到小
print(sorted([23,56546,78]))

# 排序: 由小到大, reverse=True, 代表排序后进行反转;
print(sorted([23,56546,78], reverse=True))

info = [
    ['001', 'apple', 1000, 2],
    ['002', 'xiaomi', 10, 2000],
    ['003', 'Oppo', 200, 1900],
    ['004', 'computer', 900, 5000]
]

def sorted_by_count(item):
    return item[2]

print(sorted(info, key=sorted_by_count))

# 需要按照商品的价格进行排序, 最终显示价格最高的商品名称和商品数量;

def sorted_by_price(item):
    return item[-1]
sorted_by_price_info = sorted(info, key=sorted_by_price)
print(sorted_by_price_info[-1][1], sorted_by_price_info[-1][2])


info = {
    '001':{
        'name':'apple',
        'count':1000,
        'price':2
    },

    '002': {
        'name': 'xiaomi',
        'count': 10,
        'price': 2000
    },
    '003': {
        'name': 'Oppo',
        'count': 200,
        'price': 1900
    }
}


def dict_sorted_by_count(item):
    return item['count']
print(sorted(info.values(), key=dict_sorted_by_count))
[23, 78, 56546]
[56546, 78, 23]
[['002', 'xiaomi', 10, 2000], ['003', 'Oppo', 200, 1900], ['004', 'computer', 900, 5000], ['001', 'apple', 1000, 2]]
computer 900
[{'name': 'xiaomi', 'count': 10, 'price': 2000}, {'name': 'Oppo', 'count': 200, 'price': 1900}, {'name': 'apple', 'count': 1000, 'price': 2}]
sorted函数应用
(2018-携程-春招题)题目需求:
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
    第一行是数组长度, 后续每一行是数组的一条记录;
    4
    0
    7
    0
    2
# 输出:
    调整后数组的内容;
    7
    2
    0
    0


n = int(input("数组长度:"))
li = [int(input()) for i in range(n)]
for i in sorted(li, key=lambda x: 1 if x is 0 else 0): print(i)


# def move_zero(item):
#     if item == 0:
#         return 1
#     else:
#         return 0
#
# for i in sorted(li, key=move_zero):
#     print(i)


猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/82154752