python - 使用列表值来确定哪个是父级,哪个是子级
问题描述
我将如何去转换这个
[
[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', ...],
]
新添加的(总共第二个元素)是它基于第一个元素的父编号。如果您需要更多详细信息或信息,请告诉我(这是我第一次提问)
解决方案
此代码是一个可能的两步解决方案。请注意,我使输入列表只有两个元素,您应该尝试将其修改为多元素情况以更好地理解程序,
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
。
推荐阅读
- php - 公共主机中的 Laravel 文档根目录
- latex - gnuplot:cairolatex 背景问题
- sql - 在存储过程中将 RAISERROR 替换为 THROW
- python - 是否有一个函数可以在 NumPy ndarray 周围添加(NaN)值的缓冲区?
- javascript - 在 moment-timeone 中加载特定时区不是全部。用于减小 moment-timezone webpack-bundle 的大小
- database - 如何为 DynamoDB 中的时间序列数据设计主键?
- reactjs - 反应:未处理的拒绝:无法读取未定义的属性“数据”
- python - 无法找到在 pytorchlightening 中创建 /tmp 文件的位置
- sql - 在 bigquery 中使用两列和多个条件进行左连接
- hibernate - Hibernate为插入子实体生成错误的sql查询