python中几个常用高阶函数
程序员文章站
2024-01-06 08:35:40
...
import collections
from functools import reduce
from itertools import groupby
# 计数
li = ['sunxiaohui', 'zhangzh', 'sunxiaohui', 'sunxiaohui']
counter = collections.Counter(li)
print(counter) # Counter({'sunxiaohui': 3, 'zhangzh': 1})
# 每一个key默认都是list
obj = collections.defaultdict(list)
print(obj['abc']) # []
print("*" * 80)
ll = [1, 2, 3, 4]
# map 映射每一个元素
result = map(lambda x: x * 2, ll)
print(list(result)) # [2, 4, 6, 8]
# reduce 合并两个元素
result2 = reduce(lambda x, y: x + y, ll)
print(result2) # 10
# filter 只返回True结果
result3 = filter(lambda x: x % 2 == 0, ll)
print(list(result3)) # [2, 4]
list_data = [
{"id": 101, "title": "标题1", "categroy": "python"},
{"id": 102, "title": "标题2", "categroy": "java"},
{"id": 103, "title": "标题3", "categroy": "js"},
{"id": 104, "title": "标题4", "categroy": "java"},
{"id": 105, "title": "标题5", "categroy": "go"},
{"id": 106, "title": "标题6", "categroy": "rust"},
{"id": 107, "title": "标题7", "categroy": "python"},
{"id": 108, "title": "标题8", "categroy": "js"},
{"id": 109, "title": "标题9", "categroy": "python"},
{"id": 110, "title": "标题10", "categroy": "java"},
]
arr = sorted(list_data, key=lambda x: x['categroy'])
# for v in arr:
# print(v)
result4 = groupby(arr, key=lambda x: x['categroy'])
# print(list(result4))
for key, value in result4:
print(key, list(value))
# go [{'id': 105, 'title': '标题5', 'categroy': 'go'}]
# java [{'id': 102, 'title': '标题2', 'categroy': 'java'}, {'id': 104, 'title': '标题4', 'categroy': 'java'}, {'id': 110, 'title': '标题10', 'categroy': 'java'}]
# js [{'id': 103, 'title': '标题3', 'categroy': 'js'}, {'id': 108, 'title': '标题8', 'categroy': 'js'}]
# python [{'id': 101, 'title': '标题1', 'categroy': 'python'}, {'id': 107, 'title': '标题7', 'categroy': 'python'}, {'id': 109, 'title': '标题9', 'categroy': 'python'}]
# rust [{'id': 106, 'title': '标题6', 'categroy': 'rust'}]