python查缺补漏之map(),reduce(),filter(),sorted()

这里都结合了匿名函数lambda

map()

实现对列表每个元素进行操作
map(function, iterable, …)

list_test = [4, 3, 67, 98, 56, 2, 7, 9, 1]
result = map(lambda x: x + 2, list_test)
print(list(result))

result = map(lambda s: s if s % 2 == 0 else s + 1, list_test)
print(list(result))

上面是对每个元素进行加2,下面是对奇数进行加1,结果如下

[6, 5, 69, 100, 58, 4, 9, 11, 3]
[4, 4, 68, 98, 56, 2, 8, 10, 2]

reduce()

实现对列表相邻元素迭代操作
reduce(function, sequence, initial=None)
reduce(function, iterable[, initializer])
最后一个initial是起始值,可以添加,添加后就会将该值放在列表第一个开始计算

from functools import reduce

tuple_test = (2, 4, 6, 1, 9, 5, 8)
result = reduce(lambda x, y: x + y, tuple_test)
print(result)
result = reduce(lambda x, y: x + y, tuple_test, 10)
print(result)

结果

35
45

filter()

实现对列表的过滤
filter(function, iterable)

list_test = [3, 5, 6, 1, 9, 4]
result = filter(lambda x: x > 5, list_test)
print(list(result))

结果

[6, 9]

sorted

对列表排序
sorted(iterable, cmp=None, key=None, reverse=False)
reverse决定大小顺序

dict_test = [
    {"name": 'jack', "score": 98},
    {"name": 'jam', "score": 92},
    {"name": 'bob', "score": 100},
    {"name": 'tom', "score": 90},
]
result = sorted(dict_test, key=lambda x: x["score"], reverse=True)
print(result)

结果

[{'name': 'tom', 'score': 90}, {'name': 'jam', 'score': 92}, {'name': 'jack', 'score': 98}, {'name': 'bob', 'score': 100}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值