计算机基础,Python - Map和Reduce

例子1. python中实现hashable

def __hash__(self):
    hashes = map(hash, self.components)
    return functools.reduce(operator.xor, hashes)

map函数是惰性的,和生成器表达式一样,创建一个生成器,按需产出结果,节省内存

def __hash__(self):
    #生成器表达式
    hashes = (hash(x) for x in self._components)
    return functools.reduce(operator.xor, hashes, 0)

另外:
计算机基础,Python - Map和Reduce

例子2. 计算整数0~5累计异或的三种方式

2.1 for循环

n = 0
for i in range(1, 6):
    n ^= i

2.2 reduce + lambda

import functools
functools.reduce(lambda a, b: a^b, range(6))

2.3 reduce + operator(代替lambda)

import operator
import functools
functools.reduce(operator.xor, range(6))

operator模块以函数的形式提供了Python的全部中缀运算符,从而减少使用lambda表达式。

相关文章:

  • 2021-10-21
  • 2021-04-11
  • 2022-02-07
  • 2021-07-31
  • 2021-12-24
  • 2021-12-30
  • 2022-01-28
  • 2021-10-02
猜你喜欢
  • 2021-06-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-03
  • 2021-11-03
  • 2021-10-06
  • 2021-06-24
相关资源
相似解决方案