import numpy as np
def dict_to_dicts(origin: dict, n: int):
"""
:param origin: 被拆封的字典
:param n: 被拆分几个
:return: 返回列表包字典
"""
n -= 1
keys = list(origin.keys())
dicts = []
dicts_keys = []
choose_num = 0
random_keys = np.random.choice(keys, len(keys), replace=False)
random_indexes = np.random.permutation(len(random_keys))
slice_num = min(n, len(keys))
slice_indexes = np.random.choice(random_indexes, size=slice_num, replace=False)
slice_indexes.sort()
for index in slice_indexes:
dk = random_keys[choose_num:index]
dicts_keys.append(dk)
choose_num += len(dk)
dicts_keys.append(random_keys[choose_num:])
for dict_keys in dicts_keys:
nd = {}
for key in dict_keys:
nd[key] = origin[key]
dicts.append(nd)
miss_num = n - slice_num
if miss_num:
insert_indexes = np.random.randint(0, len(dicts), miss_num)
for insert_index in insert_indexes:
dicts.insert(insert_index, {})
return dicts
主攻:Python 数据分析 web 机器学习 图像识别。。 副攻:JAVA WEB 安卓 大数据