# 1
l_1 = [2,3,5,-1,-3,0,8,-5]
for i in range(len(l_1)):
l_2 = l_1[i+1:]
for j in range(len(l_2)):
l_3 = l_2[j+1:]
for k in range(len(l_3)):
if l_3[k] + l_2[j] + l_1[i] == 0:
print(f'{l_3[k]},{l_2[j]},{l_1[i]}')
# 2
t =[tuple(sorted((x,y,z))) for x in l for y in l for z in l if x+y+z==0 and (x != y and y!=z and x != z and x!=y!=z)]
s = 'hello'
#
s[::-1]
#
''.join(reversed(s))
class A:
def __enter__(self):
print('begin')
return 'Do something'
def __exit__(self, exc_type, exc_val, exc_tb):
print(f':{exc_type}')
print(f':{exc_val}')
print(f':{exc_tb}')
print('over')
with A() as a:
print(a)
#
# begin
# Do something
# :None
# :None
# :None
# over

可迭代对象 迭代器:实现迭代器协议,即同时实现方法 iter,next 可迭代对象不一定是迭代器,迭代器一定是可迭代对象 生成器

# yield
# -
def consumer():
while True:
i = yield # send(var)vari
print(f'consumer:{i}')
def producer(c):
c.__next__() #
for i in range(5):
print(f'producer:{i}')
c.send(i) # send
print('-' * 30)
c.close()
c = consumer()
producer(c)

闭包:一个方法中嵌套另一个方法 装饰器

参考链接

#
from time import sleep,time
from functools import wraps
def duration(func):
@wraps(func)
def wrapper(*args,**kwargs):
start_time = time()
func(*args,**kwargs)
end_time = time()
print(f'{end_time - start_time}')
return wrapper
@duration
def do(name):
for i in range(10):
print(f'{i+1}name{name}')
sleep(1)
do('Jim')
#
class Decorator:
def __init__(self, func):
self.f = func
def __call__(self, *args, **kwargs):
print("__call__,begin")
self.f(*args, **kwargs)
print("__call__,end")
@Decorator
def f(a):
print(f" f:a:{a}")
f(1)
#
"""
__call__,begin
f:a:1
__call__,end
"""
#
class Decorator:
def __init__(self,x,y):
self.a = x
self.b = y
def __call__(self, f):
print("__call__,begin")
def wrap(*args,**kwargs):
print(f'__call__wrap')
f(*args,**kwargs)
print("__call__,end")
return wrap
@Decorator(1,2)
def f(a):
print(f" f:a:{a}")
f(1)
#
"""
__call__,begin
__call__,end
__call__wrap
f:a:1
"""

__call__方法

类实现__call__方法后,类实例可作为函数调用

__call__方法内可对实例属性进行更改

class A:
def __init__(self, ai, bi, ci):
self.a = ai
self.b = bi
self.c = ci
self.d = None
def __call__(self, ca, cb):
self.a = ca
self.b = cb
print(f'__call__a:{self.a},b:{self.b}')
obj_a = A(1, 2, 3)
print(f'obj_aa:{obj_a.a},b:{obj_a.b},c:{obj_a.c},d:{obj_a.d}')
obj_a(5, 6) # obj_a.__call__(5,6)
print(f'__call__obj_aa:{obj_a.a},b:{obj_a.b},c:{obj_a.c},d:{obj_a.d}')
#
"""
obj_aa:1,b:2,c:3,d:None
__call__a:5,b:6
__call__obj_aa:5,b:6,c:3,d:None
"""

字典列表排序 通过字典某个关键字进行排序

def sort_data(lst):
lst.sort(key=lambda d:d['age'],reverse=False)
l = [{'name':'jim','age':15},{'name':'tim','age':13},{'name':'cat','age':21}]
sort_data(l)
print(l)
#
# [{'name': 'tim', 'age': 13}, {'name': 'jim', 'age': 15}, {'name': 'cat', 'age': 21}]
def compare(time):
match time:
case 1:
print('1')
case 2:
print('2')
case 3:
print('3')
case _:
print('')
compare(4) #
import random
from string import ascii_letters
from string import digits
from string import punctuation
print(''.join(random.sample(ascii_letters + digits + punctuation, 16))) # sXaAv3`0{\%qx7R~
int(2.6) # 2
# n
round(12.456,2) #12.46
# n
round(123,-2) #100
round(50,-2) #0
round(50.1,-2) #100
sys._getframe().f_code.co_name
datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]) # 2021-07-02 16:26:19.160
### .join()
#
":".join(hello hi) #h:e:l:l:o: :h:i
#
":".join(('a','b','c')) #a:b:c
#
":".join(['a','b','c']) #a:b:c
#
":".join({"key1":1,"key2":2,"key3":3}) #key1:key2:key3
### .join()
import os
os.path.join('/a','/b/c','/d') #/a/b/c/d
from string import Template
mdt = {'a':123,
'b':456}
st = "{'k1':$a,'k2':$b}"
res = Template(st).safe_substitute(mdt)
print(res)
#
{'k1':123,'k2':456}

字符串列表、字符串字典,字符串表达式,转为列表、字典、python可执行代码

s = "{'amount': 100, 'price': 70.4, 'time': None}"
print(type(eval(s)))
#
<class 'dict'>
######################################
s = "[{'amount': 100, 'price': 70.4, 'time': None}]"
print(type(eval(s)))
#
<class 'list'>

查看数据编码格式包

chardet.detect(input).get('encoding')

python -c "包名"

如果没报错,则已安装

pip freeze

s = 'pri\nt'
# \
s = r'pri\nt'
tuple = 'string',
dict_1 = {
'type': 'text',
'max_length': 300
}
dict_2 = {
'type': 'html',
'max_length': 800
}
dict_3 = {
'type': 'markdown',
'max_length': 300
}
dict_4 = {
'type': 'xml',
'max_length': 600
}
dict_5 = {
'type': 'json',
'max_length': 1200
}
dict_list = [dict_1, dict_2, dict_3, dict_4, dict_5]
# —————— dict_list max_length ————————
sorted_result = sorted(dict_list, key=lambda x: x['max_length'], reverse=False)
print(sorted_result)
# Output: [{'type': 'text', 'max_length': 300}, {'type': 'markdown', 'max_length': 300}, {'type': 'xml', 'max_length': 600}, {'type': 'html', 'max_length': 800}, {'type': 'json', 'max_length': 1200}]
# —————— dict_list max_length type ————————
sorted_result = sorted(dict_list, key=lambda x: (x['max_length'], x['type']), reverse=False)
print(sorted_result)
# Output: [{'type': 'markdown', 'max_length': 300}, {'type': 'text', 'max_length': 300}, {'type': 'xml', 'max_length': 600}, {'type': 'html', 'max_length': 800}, {'type': 'json', 'max_length': 1200}]
list_1 = [5, 7, 2, 9, 0, -1, 10, 3, 2, 1, 20]
list_2 = [1, 4, 2, 6]
list_3 = ['', 0, {}, ()]
# —————— list_1,list_2True ————————
result_1 = all(list_1)
result_2 = all(list_2)
print(result_1, result_2)
# Output: False True
list_1 = [5, 7, 2, 9, 0, -1, 10, 3, 2, 1, 20]
list_2 = [1, 4, 2, 6]
list_3 = ['', 0, {}, ()]
# —————— list_1,list_2,list_3 ————————
result_1 = any(list_1)
result_2 = any(list_2)
result_3 = any(list_3)
print(result_1, result_2, result_3)
# Output: True True False
dict_1 = {
'type': 'text',
'max_length': 300
}
dict_2 = {
'type': 'html',
'max_length': 800
}
dict_3 = {
'type': 'markdown',
'max_length': 300
}
dict_4 = {
'type': 'xml',
'max_length': 600
}
dict_5 = {
'type': 'json',
'max_length': 1200
}
dict_list = [dict_1, dict_2, dict_3, dict_4, dict_5]
# —————— dict_list max_length 700 ————————
result = filter(lambda x: x['max_length'] < 700, dict_list)
print(list(result))
# Output: [{'type': 'text', 'max_length': 300}, {'type': 'markdown', 'max_length': 300}, {'type': 'xml', 'max_length': 600}]
res = map(lambda x: x * 3, (1, 2, 3))
print(list(res)) # [3, 6, 9]
res = map(lambda x,y: x * y, (1, 2, 3),(3,2,1))
print(list(res)) # [3, 4, 3]

序列化、反序列化

import json
#
mixin_dict_str = '{"time":"15:09","address":"No 110","phone":"15600000000","count":6}'
print(json.loads(mixin_dict_str)) #
# {'time': '15:09', 'address': 'No 110', 'phone': '15600000000', 'count': 6}
#
mixin_dict = {'time': '15:09', 'address': 'No 110', 'phone': '15600000000', 'count': 6}
print(json.dumps(mixin_dict,sort_keys=True))
# {"address": "No 110", "count": 6, "phone": "15600000000", "time": "15:09"}

信号通信库

blinker

支持1对1、1对多,定制主题,装饰器语法

from blinker import signal
s = signal('demo')
def run(*args):
print('Dangerous, someone begin running')
def cry(*args):
print('Dangerous, someone begin crying')
def scream(*args):
print(f'{args[0]}, someone begin scream')
def custom_theme_match(*args):
print(f'{args[0]}, ')
def custom_theme_not_match(*args):
print(f'{args[0]}, ')
@s.connect
def decorate(*args):
print(f'{args[0]}, ')
@s.connect_via('Danger is coming')
def decorate_custom_theme(*args):
print(f'{args[0]}, ')
s.connect(run)
s.connect(cry)
s.connect(scream)
s.connect(custom_theme_match, sender='Danger is coming')
s.connect(custom_theme_match, sender='Danger isn\'t coming')
s.send('Danger is coming')
#
# Danger is coming,
# Dangerous, someone begin crying
# Danger is coming, someone begin scream
# Dangerous, someone begin running
# Danger is coming,
# Danger is coming,