我有这个数组:
>>> print raw_data
['LEVEL 1',
'SUBJECT A',
'GROUP X',
'COMMENT i',
'COMMENT ii',
'COMMENT iii',
'GROUP Y',
'COMMENT iv',
'COMMENT v',
'COMMENT vi',
'LEVEL 2',
'SUBJECT B',
'GROUP Z',
'COMMENT vii',
'COMMENT viii',
'COMMENT ix',
'SUBJECT C',
'GROUP X2',
'COMMENT x',
'COMMENT xi',
'COMMENT xii',
'COMMENT xiii',
'GROUP Y2',
'COMMENT xiv',
'COMMENT xv',
'COMMENT xvi']
明显的层次结构是:
- 等级
- 学科
- 团体
- 评论
- 团体
- 学科
我的目标是将数组作为非规范化数组存储在数据库中:
>>> print result
[
['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT i'],
['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT ii'],
['LEVEL 1', 'SUBJECT A', 'GROUP X', 'COMMENT iii'],
['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT iv'],
['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT v'],
['LEVEL 1', 'SUBJECT A', 'GROUP Y', 'COMMENT vi'],
['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vi'],
['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT vii'],
['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT viii'],
['LEVEL 2', 'SUBJECT B', 'GROUP Z', 'COMMENT ix'],
['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT x'],
['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xi'],
['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xii'],
['LEVEL 2', 'SUBJECT C', 'GROUP X1', 'COMMENT xiii],'
['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xiv'],
['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xv'],
['LEVEL 2', 'SUBJECT C', 'GROUP Y2', 'COMMENT xi']
]
我试图解决这个问题,但我很迷茫,我认为这个问题必须是常见的,所以我想知道是否有人有有效的方法,这似乎是嵌套集,但我不知道python上有很多这样的东西,获得水平很容易,但我越来越“头痛”。
>>> def addlevel(a):
if a.startswith('LEVEL'):
return [1, a]
elif a.startswith('SUBJECT'):
return [2, a]
elif a.startswith('GROUP'):
return [3, a]
elif a.startswith('COMMENT'):
return [4, a]
>>> map(addlevel, raw_data)
[[1, 'LEVEL 1'],
[2, 'SUBJECT A'],
[3, 'GROUP X'],
[4, 'COMMENT i'],
[4, 'COMMENT ii'],
[4, 'COMMENT iii'],
[3, 'GROUP Y'],
[4, 'COMMENT iv'],
[4, 'COMMENT v'],
[4, 'COMMENT vi'],
[1, 'LEVEL 2'],
[2, 'SUBJECT B'],
[3, 'GROUP Z'],
[4, 'COMMENT vii'],
[4, 'COMMENT viii'],
[4, 'COMMENT ix'],
[2, 'SUBJECT C'],
[3, 'GROUP X2'],
[4, 'COMMENT x'],
[4, 'COMMENT xi'],
[4, 'COMMENT xii'],
[4, 'COMMENT xiii'],
[3, 'GROUP Y2'],
[4, 'COMMENT xiv'],
[4, 'COMMENT xv'],
[4, 'COMMENT xvi']]
我将不胜感激任何线索!