python从嵌套列表父母元素中查找值

发布于 2025-02-13 00:48:11 字数 376 浏览 3 评论 0原文

我用python保存了一个父母的结构。

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]

子列表元素的第一个索引是parentid, 子列表元素的第二个索引是childid, 子列表元素的第三个索引是值,

什么是从childid =当前parentid的子列表元素附加值的最佳和最快的方法? 新列表应该看起来像这样,

New_PC_List = [[1,1,2],[1,2,8,2],[1,3,5,2],[2,4,7,8],[3,5,1,5]]

我会很感激一些tipps。 PC_LIST的PS Len可以超过100万行。

谢谢

I saved a Parent - Child structure inside a nested list with Python.

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]

First index of sub list element is ParentID,
Second index of sub list element is ChildID,
Third index of sub list element is Value

What is the best and fastest way to append the Value from sub list element where childID = current ParentID ?
New List should look like this

New_PC_List = [[1,1,2],[1,2,8,2],[1,3,5,2],[2,4,7,8],[3,5,1,5]]

I would appreciate some tipps.
P.S. len of PC_List can go over 1Million rows.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漫雪独思 2025-02-20 00:48:12

我首先要构造一个尺寸为“ value”的映射“ id”,然后使用它来附加值。

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
values = {k: v for _, k, v in PC_List}

output = [[p, c, v, values[p]] for p, c, v in PC_List]
print(output)
# [[1, 1, 2, 2], [1, 2, 8, 2], [1, 3, 5, 2], [2, 4, 7, 8], [3, 5, 1, 5]]

I would first construct a dict that maps "id" to the "value", and then use it to append the values.

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
values = {k: v for _, k, v in PC_List}

output = [[p, c, v, values[p]] for p, c, v in PC_List]
print(output)
# [[1, 1, 2, 2], [1, 2, 8, 2], [1, 3, 5, 2], [2, 4, 7, 8], [3, 5, 1, 5]]
じее 2025-02-20 00:48:12

很难遵循您想要的东西,但是在将列表的第一个元素列为0的父元素ID之后(您使用1个索引,所以我认为没关系),我认为这可以做到您想要的:

PC_List = [[0,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
for i in range(1,len(PC_List)):
    PC_List[i].append(PC_List[PC_List[i][0]-1][2])

此解决方案更改原始列表,但可以使用copy.deepcopy修复。

It was kind of hard to follow what you wanted, but after giving the first element of the list a parent id of 0 (you're using 1-indexing so I assume that's alright), I think this does what you want:

PC_List = [[0,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
for i in range(1,len(PC_List)):
    PC_List[i].append(PC_List[PC_List[i][0]-1][2])

This solution changes the original list, but this can be fixed with copy.deepcopy if you prefer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文