python - 字典列表到相关字典列表
问题描述
我有这个清单:
list = [ { 1: [3], 2: [6] }, { 3: [4,5], 6: [8] }, { 4: [7], 5: [7] } ]
它代表了我拥有的所有对象的对象 ID 之间的整体相关性。
我想从此列表中提取的内容:
l1 = [ { 1: [3] }, { 3: [4,5] }, { 4: [7], 5: [7] } ]
l2 = [ { 2: [6] }, { 6: [8] } ]
让我来解释一下吧!
为了清楚起见,请找到下面的图片:
因此,如您所见,每个对象都由其 ID 表示。为了形成“列表”,我从左侧外围对象的 ID 开始,这些 ID 将是(“列表”的)第一个字典的键,这些键的值是连接到的对象的 ID对(我们将值放入列表中)。这些值将成为第二个字典的键(如果您有前一个字典中的重复值,则不要重复键,只需正确一次),并重复这些步骤直到达到最后一个 ID。
这些对象正在根据它们的 ID 之间的关系形成模式。在这个问题中,我将得到它们正在形成的模式的数量。在我提供链接的图片中,它们正在形成两种模式。
模式:是一组具有以某种方式相互关联的 ID 的对象
解决方案
它对我有用:
my_dict = [ { 1: [3], 2: [6] }, { 3: [4,5], 6: [8] }, { 4: [7], 5: [7] } ]
new_dict = []
# read
def read(n, p, dictionary):
a = list(dictionary[n])[p]
if len(new_dict)<=p:
new_dict.append([])
new_dict[p].append({a : dictionary[n][a]})
bucle(dictionary[n][a], n+1, p, dictionary)
def bucle(key, n, p, dictionary):
try:
for keys in key:
new_dict[p].append({keys: dictionary[n][keys]})
bucle(dictionary[n][keys], n+1, p, dictionary)
except:
pass
read(0, 0, my_dict)
read(0, 1, my_dict)
print(new_dict)
结果:
new_dict = [[{1: [3]}, {3: [4, 5]}, {4: [7]}, {5: [7]}], [{2: [6]}, {6: [8]}]]
new_dict[0] = [{1: [3]}, {3: [4, 5]}, {4: [7]}, {5: [7]}]
new_dict[1] = [{2: [6]}, {6: [8]}]
推荐阅读
- dji-sdk - DJI Windows SDK:将 Mavic 2 Pro 录制的视频保存到 SD 卡的 API 程序是什么
- json - 颠簸变换后json对象的排序
- python - 如何将 Python 对象转换为 Cython 扩展类型的 std::vector 并返回?
- postgresql - Postgres 在 funcio 中调用 Function 不是我所期望的
- python - 在 python 中向下舍入(0.10 的倍数)
- android-recyclerview - Android androidx.recyclerview 移除滚动效果
- cloud - 我在哪里可以在线获得免费的 AiX 虚拟机?
- dart - 如何在 Dart 中以有效的方式获取文件中的行数?
- php - 使用 jquery 获取动态数据
- swift - 无法在 IOS 中禁用 SSL 验证