gpt4 book ai didi

python 列表/序列格式

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:26 24 4
gpt4 key购买 nike

我有如下格式的列表列表。

[[1,3],[2,4],[3,1],[4,0],[5,1],[6,0],[7,1],[8,0 ],[9,1],[10,0],[11,3],[12,1],[13,0],[14,1],[15,0],[16,1], [17,0],[18,4],[19,1],[20,0],[21,1],[22,0],[23,1],[24,2],[25 ,0],[26,0],[27,1],[28,0].........]

或者以图形方式我的输入列表是:

[1,3]
[2,4]
[3,1]
[4,0]
[5,1]
[6,0]
[7,1]
[8,0]
[9,1]
[10,0]
[11,3]
[12,1]
[13,0]
[14,1]
[15,0]
[16,1]
[17,0]
[18,4]
[19,1]
[20,0]
[21,1]
[22,0]
[23,1]
[24,2]
[25,0]
[26,0]
[27,1]
[28,0]

在上面的输入中,列表的第一个值(零位置)是项目序列(你可以从上到下看到它们),第二个值是它有 child 的数量!

我希望我的输出在第三个值(第二个位置)我想要它的父级,如下例所示......

我想得到这样的输出:[[1,3,0],[2,4,1],[3,1,2],[4,0,3],[5,1,2],[6,0,5],[ 7,1,2],[8,0,7],[9,1,2],[10,0,9],[11,3,1],[12,1,11],[13, 0,12],[14,1,11],[15,0,14],[16,1,11],[17,0,16],[18,4,1],[19,1, 18],[20,0,19],[21,1,18],[22,0,21],[23,1,18],[24,2,23],[25,0,24] ,[26,0,24],[27,1,18],[28,0,27].....]

图形方式的期望输出:

[1,3,0]
[2,4,1]
[3,1,2]
[4,0,3]
[5,1,2]
[6,0,5]
[7,1,2]
[8,0,7]
[9,1,2]
[10,0,9]
[11,3,1]
[12,1,11]
[13,0,12]
[14,1,11]
[15,0,14]
[16,1,11]
[17,0,16]
[18,4,1]
[19,1,18]
[20,0,19]
[21,1,18]
[22,0,21]
[23,1,18]
[24,2,23]
[25,0,24]
[26,0,24]
[27,1,18]
[28,0,27]

如何解决?

最佳答案

你可以用这样的迭代器来做:

def add_parent_info(it, parent=0):
me, num_children = it.next() # For Python 3.x use next(it)
yield [me, num_children, parent]
for i in range(num_children):
for item in add_parent_info(it, me):
yield item

用法:

>>> a = [[1,3],[2,4],[3,1],[4,0],[5,1],[6,0],[7,1],[8,0],[9,1],[10,0],[11,3],[12,1],[13,0],[14,1],[15,0],[16,1],[17,0],[18,4],[19,1],[20,0],[21,1],[22,0],[23,1],[24,2],[25,0],[26,0],[27,1],[28,0]]
>>> print list(add_parent_info(iter(a)))
[[1, 3, 0], [2, 4, 1], [3, 1, 2], [4, 0, 3], [5, 1, 2], [6, 0, 5], [7, 1, 2], [8, 0, 7], [9, 1, 2], [10, 0, 9], [11, 3, 1], [12, 1, 11], [13, 0, 12], [14, 1, 11], [15, 0, 14], [16, 1, 11], [17, 0, 16], [18, 4, 1], [19, 1, 18], [20, 0, 19], [21, 1, 18], [22, 0, 21], [23, 1, 18], [24, 2, 23], [25, 0, 24], [26, 0, 24], [27, 1, 18], [28, 0, 27]]

关于python 列表/序列格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10039959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com