Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing values from list in matrix like form

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    ])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading