python 使用小技巧

合理使用一些内置函数

any() 和 all()

  • any() 有一个为真就返回True
  • all() 全为真才会返回True

1. 判断list是否包含字典(any)

def get_tag(info):
    tag = False
    for i in info:
        if isinstance(i, dict):
            tag = True
    return tag

优化后代码

def get_tag(info):
    return any(isinstance(i,dict) for i in info)

2. 判断list中对象是否都是字典(all)

def get_tag(info):
    tag = True
    for i in info:
        if not isinstance(i, dict):
            tag = False
    return tag

优化后代码

def get_tag(info):
    return all(isinstance(i,dict) for i in info)

map() 根据提供的函数对指定序列做映射

对列表元素转int

nums = ["1", "4", "0", "45", "5"]
nums = [int(i) for i in nums]

使用 map 后

nums = ["1", "4", "0", "45", "5"]
nums = map(int, nums)

两个列表,对相同位置的列表数据进行相加

map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

filter()

  • 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

eval

  • 函数用来执行一个字符串表达式,并返回表达式的值
  • 对于需要处理字符串的时候比较好用,但是有安全性问题,如果输入的是可执行脚本会有注入风险

字符串处理

a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
b = eval(a)
# [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]

python 的一些其他用法

共享文件夹

  1. 进入到指定目录,执行 python -m http.server

  2. 访问地址 http://[::]:8000/,点击文件可以实现下载

控制台格式化输出转json

  • | python -m json.tool

函数缓存

from functools import lru_cache

@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

自定义上下文管理器 打开文件

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):
        self.file_obj.close()

with File('demo.txt', 'w') as opened_file:
    opened_file.write(' hello!')

执行过程步骤:

  1. with 语句先暂存了 File 类的__exit__方法
  2. 然后它调用 File 类的__enter__方法
  3. __enter__方法打开文件并返回给 with 语句
  4. 打开的文件句柄被传递给 opened_file 参数
  5. 我们使用.write()来写文件
  6. with语句调用之前暂存的__exit__方法
  7. __exit__方法关闭了文件

注:
type, value, traceback 如果发生异常,会将异常的类型,值,详细信息,如果 __exit__ 返回 True 则不会抛出异常,否则会抛出异常,可以自行在 __exit__ 中处理异常

使用 contextmanager 装饰器实现上下文管理器

from contextlib import contextmanager

@contextmanager
def open_file(name):
    f = open(name, 'w')
    yield f
    f.close()

实际使用例子

from contextlib import contextmanager

@contextmanager
def redis_ctx():
    redis_cli = Redis()
    try:
        yield redis_cli
    finally:
        redis_cli.close()

def get_redis_value(key):
    with redis_ctx() as redis_cli:
        return redis_cli.read(key)

posted @ 2022-03-02 09:32  今日店休  阅读(27)  评论(0编辑  收藏  举报