Daibingh Less is more, slow is fast.

python 高级用法

2019-11-27
hdb

返回生成器

yield 是一个类似 return 的关键字,只是这个函数返回的是个生成器,当你调用这个函数的时候,函数内部的代码并不立马执行 ,这个函数只是返回一个生成器对象。当你使用for进行迭代的时候,函数中的代码才会执行。

sys.modules 全局字典的运用

sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules都将记录这些模块。字典sys.modules对于加载模块起到了缓冲的作用。当某个模块第一次导入,字典sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。

字典sys.modules具有字典所拥有的一切方法,可以通过这些方法了解当前的环境加载了哪些模块

import sys
sys.modules # 代表内存中加载的模块组成的字典
sys.modules.keys() #查看加载的模块的名称
sys.modules.values() # 查看加载的模块对象
sys.modules['modules_name'] # 返回某一模块对象
sys.modules[__name__] # 返回当前模块对象

例如:

getattr(sys.modules[__name__], 'fun') # 获取当前模块中的 fun 变量(函数)

python 静态函数 使用@staticmethod装饰

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        pass

调用时,直接 C.f(), 也可以实例化再调用。

使用 __future__模块

Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。

列表推导

    单变量:[x for x in list_a if condition]
    多变量:[x+y for x, y in zip(list_a, list_b)]
    嵌套: gen = (item for sl in nested_list if list_condition(sl) \
                          for item in sl if item_condition(item))

变量交换

    a, b = b, a

返回生成器

def my_range(n):
    i = 0
    result = []
    while i < n:
        yield fn(i)  #  使用生成器代替列表
        i += 1
# 尽量用生成器代替列表,除非必须用到列表特有的函数。

带索引遍历

for i, item in enumerate(items):
    print i, item

循环嵌套

# 不推荐
for x in x_list:
   for y in y_list:
       for z in z_list:
           # do something for x & y  

# 推荐
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
   # do something for x, y, z

使用 any和all

if any(condition(item) for item in a_list):
   # do something if found...

使用with打开文件

with open("some_file.txt") as f:
   data = f.read()
   # 其他文件操作...

访问字典

d = {'hello': 'world'}

print d.get('hello', 'default_value') # prints 'world'
print d.get('thingy', 'default_value') # prints 'default_value'

遍历字典

for k in a.keys():
    print(k)
for v in a.values():
    print(v)
for k,v in a.items():
    print(k,v)

使用占位符

filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')

链式比较

if 18 < age < 60:
    print("young man")

使用 in

# 不推荐
if fruit == "apple" or fruit == "orange" or fruit == "berry":
   # 多次判断  
   
# 推荐
if fruit in ["apple", "orange", "berry"]:
   # 使用 in 更加简洁

使用 assert 断言,增强代码的健壮性

assert expression

获取字典最小值所对应的 key

min(d, key=d.get)

两个 list 交集

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

类内的一些功能函数

  • __str__: 调用 print() 时默认执行的函数
  • __repr__: 调用 repr() 时默认执行的函数, 用于将对象转换成可以被解释器解析的字符串命令
  • __call__: 实例当成函数调用时所执行的函数

使用 super()

http://funhacks.net/explore-python/Class/super.html

Variables inside and outside of __init__()

  • Variable set outside init belong to the class. They’re shared by all instances.
  • Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.

使用 partial 函数

  • partial 的功能:固定函数参数,返回一个新的函数。
  • 当函数参数太多,需要固定某些参数时,可以使用 functools.partial 创建一个新的函数。
from functools import partial

def multiply(x, y):
    return x * y
    
double = partial(multiply, y=2)

多进程

  • 单参数函数执行并计算 map
      import multiprocessing
        
      def f(x):
          return x*x
        
      # Get all cores
      cores = multiprocessing.cpu_count()
      # start a pool
      pool = multiprocessing.Pool(processes=cores)
        
      tasks = [1,2,3,4,5]
        
      # do parallel calculate
      print(pool.map(f,tasks))
    
  • 多参数函数执行并行计算 starmap
      import multiprocessing
        
      def add(x, y):
        return x+y
        
      # Get all worker processes
      cores = multiprocessing.cpu_count()
        
      # Start all worker processes
      pool = multiprocessing.Pool(processes=cores)
      x1 = list(range(5))
      y1 = list(range(5))
        
      tasks = [(x,y) for x in x1 for y in y1]
        
      print(pool.starmap(add,tasks))
    
  • More …
      from functools import partial
      from itertools import repeat
      from multiprocessing import Pool, freeze_support
        
      def func(a, b):
          return a + b
        
      def main():
          a_args = [1,2,3]
          second_arg = 1
          with Pool() as pool:
              L = pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
              M = pool.starmap(func, zip(a_args, repeat(second_arg)))
              N = pool.map(partial(func, b=second_arg), a_args)
              assert L == M == N
        
      if __name__=="__main__":
          freeze_support()
          main()
    
  • multiprocessing 在 windows 和 jupyter 出现问题
    • windows 脚本中必须有 if __name__ == '__main__'
    • windows jupyter 中始终阻塞
    • https://medium.com/@grvsinghal/speed-up-your-python-code-using-multiprocessing-on-windows-and-jupyter-or-ipython-2714b49d6fac

python 调用 Shell命令

  • 最简单方法:os.system(cmd)

https://blog.csdn.net/u010454729/article/details/46640083

python 设置环境变量

>>> import os
>>> os.environ.has_key('HOME')  # Check an existing env. variable
True
>>> os.environ.has_key('FOO')   # Check a non existing variable
False
>>> os.environ['FOO'] = '1'     # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO')       # Retrieve the value
'1'

Similar Posts

上一篇 爬虫小结

Comments