首页 > 解决方案 > 字典列表到相关字典列表

问题描述

我有这个清单:

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 的对象

标签: pythonlistdictionary

解决方案


它对我有用:

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]}]

推荐阅读