Python笔记

2023-01-31 00:01:36 python 笔记
  • 列表[List] 元组(truple) 字典{dict}
# 列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推
# list comprehension
[i for i in range(10)]
# 元组与列表类似,不同之处在于元组的元素不能修改
# truple generator
(i for i in range(10))
# 字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中
# dict comprehension
{k:1 for k in range(10)}
  • 生成器(generator)
    带有 yield 的函数在 python 中被称之为 generator(生成器)
def my_range(n):
    i = 0
    while i != n:
        i += 1
        yield i


r = my_range(10)
for i in r:
    print(i)
  • 迭代器 iterator
    • 迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退
while True:
    try:
        i = next(iter_obj)
    except StopIteration:
        break

class Pow2(object):
    def __init__(self, max):
        self.max = max
        self.n = 0

    def __iter__(self):
        self.n = 0
        return self

    def __next__(self):
        if self.n < self.max:
            self.n += 1
            return 2 ** self.n
        else:
            raise StopIteration


p = Pow2(10)
for i in p:
    print(i)
  • 实例方法(instance method), 类方法(class method), 静态方法(static method)
# instance method 
a = A() a.foo() a.bar()
# class method bind class
# static method

class A(object):
    @staticmethod
    def s_foo():
        pass

    @claSSMethod
    def c_foo(cls):
        pass

    def foo(self):
        pass

a = A()
a.foo()
A.c_foo()
  • 深拷贝 浅拷贝
# 深拷贝
from copy import deepcopy
l1 = []
l2 = deepcopy(l1)
l1.append(1)
print(l2)

# 浅拷贝
l1 = [1, [1, 2], 3]
l2 = l1[:]

def foo(a=[]):
    a.append(1)
    print(a)
foo()
foo()
  • lambda表达式, 闭包(closure)
    • lambda
     import functools
     import operator
     mul2 = lambda x: 2 * x
     print(mul2(3))
    
     print(list(map(lambda x: 3 * x, [1, 2, 3, 4])))
     print(list(filter(lambda x: x % 3 == 0, [1, 2, 3, 4])))
     print(functools.reduce(operator.add, [1, 2, 3, 4, 5], 5))
    • closure
     # 例子一
     def greeting(msg):
         def hello(name):
             print(msg, name)
         return hello
    
     h = greeting("welcome")
     h("akira")
    
     # 例子二
     l = []
     for i in range(10):
         def _(i=i):
             print(i)
         l.append(_)
    
     for f in l:
         f()
  • *args, **kwargs
    args获取tuple, kwargs获取kwargs
def log(*args, **kwargs):
    print("args", args)
    print("kwargs", kwargs)
log(1, 2, 3, 4)
log(1, 2, [1, 2, 3], c=4)
  • 递推式构造列表
# list comprehension
r1 = [i for i in range(10)]
print(r1)
# dict comprehension
r2 = {k:1 for k in range(10)}
print(r2)
# list generator
r3 = (i for i in range(10))
print(list(r3))
  • 装饰器(decorator)
    可用于aop(aspect oriential programming)
    例如:
if debug:
    xxx
else:
    yyy

decorator例子

def simple_wrapper(fn):
    def _():
        #print(fn.__name__)
        return fn()
    return _

def fix_arg_wrapper(fn):
    def _(x):
        #print(fn.__name__)
        return fn(x)
    return _

def all_args_wrapper(fn):
    def _(*args, **kwargs):
        print(*args, **kwargs)
        return fn(*args, **kwargs)
    return _

@simple_wrapper
def foo():
    pass

@all_args_wrapper
def bar(a, b, c):
    pass

foo()
bar(1, 2, 3)
  • 魔法方法(magic method)

形如:
__xxx__

例子:

class LogAll(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3
    def __getattribute__(self, item):
        print(item)

l = LogAll()
print(l.a)
l.a = 1
l.b
l.c

class Any(object):
    def __getattr__(self, item):
        print(item)

    def __setattr__(self, key, value):
        print("set", key, value)

a = Any()
a.a
a.a = 1

class Any2(object):
    def __getattr__(self, item):
        def _(*args, **kwargs):
            print("function name", item)
            print("args", args)
            print("kwargs", kwargs)

        setattr(self, item, _)

        return _


a = Any2()
a.a1(1, 2, 3)
a.a2(1, 2, [1, 2, 3], c=[])
  • Mixin模式
    例子:
class A(object):
    def foo(self):
        print("foo")
    def bar(self):
        print("bar")
        self.shit()

class B(object):
    def shit(self):
        print("shit")

class C(A, B):
    pass

c = C()
c.bar()
  • 字符串反转
new_x = str_x[::-1]
  • 关于i++
    Python 中的没有 i++ ,如果写了会报语法错误。
    但是python 中有 --i,++i,+-i,-+i,他们不是实现-1操作的,仅仅是作为判断运算符号,类似数学中的负负得正
i = 2
print ++i  //2
print -+i   //-2
print +-i  //-2
print --i   //2
  • 逻辑表达式
    python 中没有 && ,!, || 这3个运算符,在逻辑表达式中写成这3个会抱逻辑错误的。要实现同样的功能,要写成 and,not,or
    返回值 2 and 3 返回3
    返回值 2 or 3 返回2
    返回值 not 2 and 3 返回 False

  • if-elif-else的写法
    例如:比较两个二叉树是否相同
class Treenode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSameTree(self, p: 'TreeNode', q: 'TreeNode') -> 'bool':
        if p is None and q is None:
            return True
        elif p is not None and q is not None:
            if p.val == q.val:
                return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
            else:
                return False
        else:
            return False
  • 其它
top_element = stack.pop() if stack else '#'

相当于

if stack:
    top_element = stack.pop()
else:
    top_element = '#'

相关文章