Adding a single 'counter' to each element of an array of lists

Question:

I’ve got a .dat file that i I’ve pulled the data from and i was using the tabulate plug in to tidy it up and put it into tables. However, part of the question is to add a position column or counter. It should be simple enough to add one element at the start of each list in my array but i am having an absolute nightmare…

the code for pulling in the data from the .dat file is:

def readToDictionary():
    global dicts
    fi = open('CarRegistry.dat', 'r')

    dicts = []
    buffer = []

    while True:
              
        team = fi.readline()
        if not team: break

        fields = team.split(',')
        buffer.append(fields)

    fi.close()

    dicts = buffer
    print(dicts)
    
    return dicts

Im duplicating the array deliberately as i need to do some other functions on it and want to keep the original data intact.

The raw out put is:
[[‘1’, ‘BD61 SLU’, ‘HONDA’, ‘CR-V’, ‘SFDR’, ‘5’, ‘1780’, ‘4510’, ‘130’, ’39’, ‘Truen’], [‘2’, ‘CA51 MBE’, ‘CHEVROLET’, ‘CORVETTE’, ‘JTAV’, ‘2’, ‘1877’, ‘1234’, ‘194’, ’24’, ‘Truen’], [‘3’, ‘PC14 RSN’, ‘FORD’, ‘F-150’, ‘PQBD’, ‘5’, ‘2121’, ‘5890’, ‘155’, ’20’, ‘Truen’], [‘4’, ‘MB19 ORE’, ‘HONDA’, ‘ACCORD’, ‘FDAR’, ‘5’, ‘1849’, ‘4933’, ‘125’, ‘47.3’, ‘Falsen’], [‘5’, ‘BD68 NAP’, ‘HONDA’, ‘ACCORD’, ‘FDAV’, ‘5’, ‘1849’, ‘4933’, ‘171’, ‘37.7’, ‘Falsen’]…

what i want to get to is:

[[‘1’, ‘1’, ‘BD61 SLU’, ‘HONDA’, ‘CR-V’, ‘SFDR’, ‘5’, ‘1780’, ‘4510’, ‘130’, ’39’, ‘Truen’], [‘2’, ‘2’, ‘CA51 MBE’, ‘CHEVROLET’, ‘CORVETTE’, ‘JTAV’, ‘2’, ‘1877’, ‘1234’, ‘194’, ’24’, ‘Truen’], [‘3’, ‘3’, ‘PC14 RSN’, ‘FORD’, ‘F-150’, ‘PQBD’, ‘5’, ‘2121’, ‘5890’, ‘155’, ’20’, ‘Truen’], [‘4’, ‘4’, ‘MB19 ORE’, ‘HONDA’, ‘ACCORD’, ‘FDAR’, ‘5’, ‘1849’, ‘4933’, ‘125’, ‘47.3’, ‘Falsen’], [‘5’, ‘5’, ‘BD68 NAP’, ‘HONDA’, ‘ACCORD’, ‘FDAV’, ‘5’, ‘1849’, ‘4933’, ‘171’, ‘37.7’, ‘Falsen’]…

It’s basically a counter at the start of each list.

Ive tried all sorts and just keep getting errors, probably because i cant understand the basics of why i cant just do this:


    for i in buffer:
        buffer.insert(i, i+1)

to go through each entry in the list and add a value equal to the index +1… I know its probably simple but i’ve been banging my head off the monitor for a good few hours now…

Asked By: T1m_McG

||

Answers:

The key is, you don’t want to manipulate buffer. You want to manipulate the individual lists within buffer:

for i,row in enumerate(buffer):
    row.insert( 0, str(i+1) )
Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.