zoukankan      html  css  js  c++  java
  • 计算机基础,Python

    例子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)
    

    另外:

    例子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表达式。

  • 相关阅读:
    多态
    抽象类和接口
    面向对象3
    类的继承 设计模式
    面向对象2
    面向对象
    复习
    对json的简单认识
    关于AJAX
    PHP配置开发环境
  • 原文地址:https://www.cnblogs.com/allen2333/p/8863849.html
Copyright © 2011-2022 走看看