我正在解析一个文件,其中标签定义如下,层次结构使用新行表示
+--------------------+--------------------+--------------------+
| 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']
]
我手头有点时间,想知道我该怎么解决这个问题。你知道吗
所以这是我的解决方案,也许能激发一些想法:
active = x if x else active
在这一行中,如果x为None,则保持active的原始值,但是,在检查所需的输出时,如果达到元组的计数,则需要一种将active重置为None的方法。你知道吗下面是我如何实现你想要的输出
我得到了结果
希望能解决你的问题
以下是joinfoo的一个版本,它提供了您想要的:
每次y项切换回无时,您也希望“active”切换回无。你知道吗
顺便说一句,正如它写的joinfoo不适用于加入任何超过3个列表。如果你需要的话
用
result.append((active, *y))
替换result.append((active, y[0], y[1]))
。你知道吗相关问题 更多 >
编程相关推荐