gpt4 book ai didi

python - 列表列表中的非规范化层次结构

转载 作者:行者123 更新时间:2023-11-30 22:13:58 25 4
gpt4 key购买 nike

我正在解析一个文件,其中标签定义如下,并使用换行符表示层次结构

+--------------------+--------------------+--------------------+
| L1 - A | | |
| | L2 - B | |
| | | L3 - C |
| | | |
| L1 - D | | |
| | L2 - E | |
| | | L3 - F |
+--------------------+--------------------+--------------------+

我将以上表示为:

labels = [
['A', None, None, None, 'D', None, None],
[None, 'B', None, None, None, 'E', None],
[None, None, 'C', None, None, None, 'F']
]

我试过了

def joinfoo(items):
if len(items) == 1:
return items[0]

result = []
active = None
for x, y in zip(items[0], joinfoo(items[1:])):
active = x if x else active
if type(y) is tuple:
result.append((active, y[0], y[1]))
else:
result.append((active, y))

return result

我想要

[
('A', None, None), ('A', 'B', None), ('A', 'B', 'C'),
(None, None, None),
('D', None, None), ('D', 'E', None), ('D', 'E', 'F')
]

得到了这个

[
('A', None, None), ('A', 'B', None), ('A', 'B', 'C'),
('A', 'B', None),
('D', 'B', None), ('D', 'E', None), ('D', 'E', 'F')
]

有关如何修复 joinfoo() 以达到预期结果的建议?解决方案需要支持可变数量的列。

它应该类似于 for x, y in zip(joinfoo(items[:-1]), items[-1]): 而不是 for x, y in zip (items[0], joinfoo(items[1:])): 朝正确的方向前进...?

编辑:原始的列表列表可能错误地暗示了层次结构的模式。没有明确的模式。列数也是可变的。也许是一个更好的测试用例..

+--------------+--------------+--------------+
| L1 - A | | | = A
| | L2 - B | | = A - B
| | | L3 - C | = A - B - C
| | | L3 - D | = A - B - D
| | L2 - E | | = A - E
| | | | =
| L1 - F | | | = F
| | L2 - G | | = F - G
| | | L3 - H | = F - G - H
+--------------+--------------+--------------+

labels = [
['A', None, None, None, None, None, 'F', None, None],
[None, 'B', None, None, 'E', None, None, 'G', None],
[None, None, 'C', 'D', None, None, None, None, 'H']
]

最佳答案

我花了一些时间,想知道如何解决这个问题。

这是我的解决方案,也许它会激发一些想法:

labels = """\
+--------------------+--------------------+--------------------+
| L1 - A | | |
| | L2 - B | |
| | | L3 - C |
| | | |
| L1 - D | | |
| | L2 - E | |
| | | L3 - F |
+--------------------+--------------------+--------------------+
"""

lines = [[(s.strip()[-1:] if s.strip() else None)
for s in line[1:-1].split('|')]
for line in labels.splitlines()[1:-1]]

for index, labels in enumerate(lines):
if not any(labels):
continue
for i, label in enumerate(labels):
if label:
break
if not label:
lines[index][i] = lines[index-1][i]

print([tuple(labels) for labels in lines])

# --> [('A', None, None), ('A', 'B', None), ('A', 'B', 'C'), (None, None, None), ('D', None, None), ('D', 'E', None), ('D', 'E', 'F')]

关于python - 列表列表中的非规范化层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636877/

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