首页 > 解决方案 > 使用列表值来确定哪个是父级,哪个是子级

问题描述

我将如何去转换这个

[
    [1, '025', ...],
    [1, '026', ...],
    [2, '027', ...],
    [2, '028', ...],
    [3, '029', ...],
    [3, '030', ...],
    [2, '031', ...],
    [2, '032', ...],
]

进入这个

[
    [1, None, '025', ...],
    [1, None, '026', ...],
    [2, '026', '027', ...],
    [2, '026','028', ...],
    [3, '028','029', ...],
    [3, '028','030', ...],
    [2, '026','031', ...],
    [2, '026','032', ...],
]

新添加的(总共第二个元素)是它基于第一个元素的父编号。如果您需要更多详细信息或信息,请告诉我(这是我第一次提问)

标签: python

解决方案


此代码是一个可能的两步解决方案。请注意,我使输入列表只有两个元素,您应该尝试将其修改为多元素情况以更好地理解程序,

raw_list = [[1, '025'], [1, '026'],
                [2, '027'], [2, '028'],
                [3, '029'], [3, '030'],
                [2, '031'], [2, '032']]

with_parents = []

# Find all parents (second sublist with the
#   the same first element)
# first element converted to string : [second element, counter]
parent_dict = {}
for elem in raw_list:
    el_id = str(elem[0])
    if el_id in parent_dict:
        # Check the counter, replace if second
        if parent_dict[el_id][1] == 1:
            parent_dict[el_id][1] += 1
            parent_dict[el_id][0] = elem[1]
        else:
            continue
    else:
        # If there is only one occurence, this persists 
        parent_dict[el_id] = [elem[1], 1]

# Create the parent - child list
for elem in raw_list:
    # ID of the parent
    p_id = str(elem[0]-1)
    # No parents
    if p_id == '0':
        with_parents.append([elem[0], None, elem[1]])
    else:
        # Look up and insert parent and child info
        with_parents.append([elem[0], parent_dict[p_id][0], elem[1]])

第一步,代码将有关父母的信息收集到字典中。有多种方法可以做到这一点,也更有效。在这里,我们遍历整个列表并简单地收集每个 ID 的第二个元素(子列表中的第一个条目)。ID 成为字典键,字典条目存储您以后要使用的父值,以及一个计数器。计数器指示已存储的值是否是raw_list. 该字典便于以后访问父数据,并使其对不连续的 ID 有效(例如,如果您有 1、2、3、5、6 - 即缺少 4)。

在第二步中,代码构建最终的父子列表。它再次遍历列表,这次在步骤 1 中构建的字典中查找正确的父级。它将父级和子级信息保存到另一个列表中,最后一个,with_parents. 它将条目ID = 1视为特殊情况。

请注意,如果 中只有一个父条目raw_list,则该条目将是列表中使用的条目with_parents


推荐阅读