I have the following list L for which I’m trying to store the values in "rows" logic locating each value
in the position given by dictionary HeadersPositions.
This is my current code, for which I tried while element[0] != "V": in order to change to a next row after get the last header that is V for each "row", but I got an infinite loop, then I changed to if element[0] != "V": in order to control when to switch to next row but is only storing in list row, the first position of header B
L = [
['B', 3],
['T', 0],
['N', 5],
['V', 2],
['N', 1],
['V', 4],
['B', 7],
['T', 2],
['N', 9],
['V', 1],
['B', 1],
['N', 8],
['V', 3]
]
HeadersPositions = {'B': 0, 'T': 1, 'N': 2, 'V': 3}
rows = []
row=[None]*len(HeadersPositions)
for element in L:
if element[0] != "V":
row.insert(HeadersPositions[element[0]], element[1])
rows.append(row)
My desired output is
Out = [
[3,0,5,2],
[none,none,1,4],
[7,2,9,1],
[1,none,8,3],
]
Seen like table would be like this:
B T N V
3 0 5 2
1 4
7 2 9 1
1 8 3
>Solution :
Having renamed L to data (since L is a capital letter and l would also not be a recommended variable name):
data = [
['B', 3],
['T', 0],
['N', 5],
['V', 2],
['N', 1],
['V', 4],
['B', 7],
['T', 2],
['N', 9],
['V', 1],
['B', 1],
['N', 8],
['V', 3]
]
headers_positions= {'B': 0, 'T': 1, 'N': 2, 'V': 3}
rows = []
while data:
rows.append([
data.pop(0)[1] if data and data[0][0] == h else None
for h in headers_positions.keys()
])
print(rows)
Output:
[[3, 0, 5, 2], [None, None, 1, 4], [7, 2, 9, 1], [1, None, 8, 3]]
Note: this is ignoring the values of the HeadersPositions, and you should probably use a list there if that’s OK.
Otherwise:
headers_positions = {'B': 0, 'T': 1, 'N': 2, 'V': 3}
headers = [k for k, v in sorted(headers_positions.items(), key=lambda h: h[1])]
rows = []
while data:
rows.append([
data.pop(0)[1] if data and data[0][0] == h else None
for h in headers
])