一维列表展开为二维列表

  1. A = [1, 3, 4, 4, 5, 5]
  2. list(zip(*[iter(A)] * 2))
  3. """
  4. [(1, 2), (3, 4), (5, 6)]
  5. """

二维列表展开为一维列表

  1. B = [(1, 2), (3, 4), (5, 6)]
  2. import itertools
  3. print(list(itertools.chain.from_iterable(B)))
  4. """
  5. [1, 2, 3, 4, 5, 6]
  6. """

使用*访问列表中的每个元素

  1. # * 访问列表的所有元素
  2. def summation(*arg):
  3. sum = 0
  4. for i in arg:
  5. sum += 1
  6. return sum
  7. result = summation([1, 2, 4, 4]) # 这种传参方式会把列表当作可变位置参数的一项,见下文截图
  8. print(result)

image.pngimage.png

在同一行中打印多个元素

  1. print("111", '2222', end=' ')
  2. print('3333', end='\n')
  3. """
  4. 111 2222 3333
  5. """

在一行代码中合并 2 个字典

  1. first_dct = {"a": 1, "b": 2}
  2. second_dct = {"c": 3, "d": 4}
  3. print({**first_dct, **second_dct})
  4. """
  5. {'a': 1, 'b': 2, 'c': 3, 'd': 4}
  6. """

for实现死循环

  1. # iter除了可以将列表转化为迭代器,还能接受一个callable对象,和一个sentinel参数,当第一个对象返回sentinel值才结束
  2. for i in iter(int, 1):
  3. pass

关闭异常自动关联上下文

  1. try:
  2. print(1 / 0)
  3. except Exception as exc:
  4. raise RuntimeError("something bad happened")
  5. """
  6. Traceback (most recent call last):
  7. File "/home/worktests/base/descriptor_test.py", line 344, in <module>
  8. print(1 / 0)
  9. ZeroDivisionError: division by zero
  10. During handling of the above exception, another exception occurred:
  11. Traceback (most recent call last):
  12. File "/home/work/base/descriptor_test.py", line 346, in <module>
  13. raise RuntimeError("something bad happened")
  14. RuntimeError: something bad happened
  15. """
  16. # 通过from 限制新异常是由哪个异常引起的
  17. try:
  18. print(1 / 0)
  19. except Exception as exc:
  20. raise RuntimeError("something bad happened") from exc
  21. """
  22. Traceback (most recent call last):
  23. File "/home/work/tests/base/descriptor_test.py", line 364, in <module>
  24. print(1 / 0)
  25. ZeroDivisionError: division by zero
  26. The above exception was the direct cause of the following exception:
  27. Traceback (most recent call last):
  28. File "/home/workts/base/descriptor_test.py", line 366, in <module>
  29. raise RuntimeError("something bad happened") from exc
  30. RuntimeError: something bad happened
  31. """
  32. # 使用raise ... from None 彻底关闭自动关联异常上下文
  33. try:
  34. print(1 / 0)
  35. except Exception as exc:
  36. raise RuntimeError("something bad happened") from None
  37. """
  38. Traceback (most recent call last):
  39. File "/home/work/tests/base/descriptor_test.py", line 387, in <module>
  40. raise RuntimeError("something bad happened") from None
  41. RuntimeError: something bad happened
  42. """

使用自带缓存机制

  1. from functools import lru_cache
  2. """
  3. maxsize: 最多可以缓存多少个此函数的调用结果,为None时无限制
  4. typed:为true,则不同参数类型的调用分别缓存
  5. """
  6. # @lru_cache(maxsize=1, typed=True)
  7. @lru_cache(None)
  8. def add(x, y):
  9. print("计算结果:%s + %s" % (x, y))
  10. return x + y
  11. print(add(2, 8))
  12. print(add(22, 8))
  13. print(add(222, 8))
  14. print(add(2, 8))
  15. # 计算结果:2 + 8
  16. # 10
  17. # 10
  18. # 10

流式读取超大文件

  1. filename = "test.py"
  2. def read_file(filename, block_size = 1024 * 8):
  3. with open(filename, "r") as fp:
  4. while True:
  5. chunk = fp.read(block_size) # 设置读取多少个字符
  6. if not chunk:
  7. print("已读取完毕")
  8. break
  9. yield chunk
  10. res = read_file(filename=filename)
  11. print(res) # 生成器对象
  12. for i in res:
  13. print(i)

逗号的独特用法

  1. # 元组的转化
  2. def func():
  3. return "test",
  4. print(func()) # ('test',)

运行代码时查看源代码

  1. # 运行代码查看源代码
  2. import inspect
  3. def add(x, y):
  4. return x + y
  5. print("#"* 90)
  6. print(inspect.getsource(add))

字典访问不存在的key不报错

  1. # 方式一
  2. import collections
  3. profile = collections.defaultdict(int)
  4. # 使用匿名函数
  5. # profile = collections.defaultdict(lambda : "this is default value")
  6. print(profile["a"]) # 0
  7. profile["a"] = 1
  8. print(profile["a"]) # 1
  9. # 方式二
  10. profile1 = {}
  11. print(profile1["a"]) # KeyError: 'a'
  12. print(profile1.get("a", 100)) # 100

利用any替换for循环

  1. # 利用any 替代for循环
  2. things = [2, 4, 1, 3]
  3. found = False
  4. for thing in things:
  5. if thing == 1:
  6. found = True
  7. break
  8. print("found: {}".format(found))# found: True
  9. # 等同上for循环效果
  10. found_2 = any(thing == 1 for thing in things)
  11. print("found_2: {}".format(found_2)) # found_2: True

parse库-优雅解析规范的字符串

  1. from parse import parse
  2. before_data = (
  3. 'cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480'
  4. )
  5. print(f"before_data: {before_data}")
  6. # before_data: cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480
  7. parse_result = parse('cookie={cookie}, duration={duration}, table={table}, n_packets={n_packets}', before_data)
  8. print(f"parse_result: {parse_result}")
  9. # parse_result: <Result () {'cookie': '0x9816da8e872d717d', 'duration': '298506.364s', 'table': '0', 'n_packets': '480'}>
  10. print(f'cookie: {parse_result["cookie"]}') # cookie: 0x9816da8e872d717d
  11. # 解析没有定义字段名字的情况
  12. before_data_2 = 'I am zaygee, 26 years old'
  13. parse_2_result = parse("i am {}, {} years old", before_data_2)
  14. print(f"parse_2_result: {parse_2_result}") # parse_2_result: <Result ('zaygee', '26') {}>
  15. # 解析类似字典的实例的情况
  16. parse_3_result = parse("i am {name}, {age} years old", before_data_2)
  17. print(f"parse_3_result: {parse_3_result}") # parse_3_result: <Result () {'name': 'zaygee', 'age': '26'}>
  18. print(parse_3_result["name"]) # zaygee

根据进程名称模糊匹配获取pid

  1. import subprocess
  2. from typing import List
  3. def get_pid_by_process_name(name: str)->List[int]:
  4. """根据进程名称grep 匹配获取pid"""
  5. results = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
  6. response = results.communicate()[0]
  7. return [int(pid) for pid in response.decode('utf-8').split() if response]
  8. if __name__ == '__main__':
  9. get_pid_by_process_name(name='tongxue')