Let me demonstrate my issue with an example. I have a data structure that looks like the one provided below:
[
[['A', 'B'], '1', '1...'],
[['A', 'B'], '2', '2...'],
[['A', 'C'], '3', '3...'],
[['A', 'C'], '4', '4...'],
[['A', 'A'], '5', '5...'],
[['A', 'D'], '6', '6...'],
[['C', 'A'], '7', '7...'],
[['D', 'C', 'B'], '8', "8..."],
[['D', 'A', 'B'], '9', "9..."],
[['D', 'A', 'A', 'Y'], '10', "10..."],
[['D', 'A', 'A', 'X'], '11', "11..."]
]
Each element starts with a list (the number of elements in this list is unknown), followed by two element (the last two elements are not important, they are just text). I want to create a new structure from this list. I want to combine elements based on their first element, like this:
'A'
'A'
'5', '5...'
'B'
'1', '1...'
'2', '2...'
'C'
'3', '3...'
'4', '4...'
'D'
'6', '6...'
'C'
'A'
'7', '7...'
'D'
'A'
'A'
'X'
'11', '11...'
'Y'
'10', '10...'
'D'
'A'
'B'
'9', '9...'
'C'
'B'
'8', '8...'
So the first element(in the first list) acts as the first level, the second element as the second level and so on.
I hope you can see what I am trying to do! I was hoping to use sort()
and then use itemgetter
and groupby
but I then saw the number of elements are different in each list. How should I solve this problem?
I need to create this new structure in order to create a proper XML of the original input.