LeLuc
LeLuc

Reputation: 415

Converting roman numerals to integers in a list of lists

I have a large list if lists (this is just some of the top rows):

['001-008  I', 'I', 'Enfermedades infecciosas y parasitarias', 2018, 6.398]
['001-008  I', 'I', 'Enfermedades infecciosas y parasitarias', 2017, 6.819]

And want to apply a function that I have to convert the second column to integers and add it behind the second column, so that the output would look as follows (don't mind the last two columns):

['001-008 I', 'I', 1, 'Enfermedades infecciosas y parasitarias', 1984, 3232]
['001-008 I', 'I', 1, 'Enfermedades infecciosas y parasitarias', 1992, 16]

The function I wrote before is:

def roman_to_int(r):
    rom_vals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 
    result = 0 
    for i,c in enumerate(r):
        if (i+1) == len(r) or rom_vals[c] >= rom_vals[r[i+1]]: 
            result += rom_vals[c]
        else:
            result -= rom_vals[c]
    return(result)

I've tried a list comprehension and concatenation, but it seems you can't concatenate a function. I was able to return the list of only the converted values (integers), but wasn't able to add it to the initial list.

Upvotes: 0

Views: 161

Answers (1)

goalie1998
goalie1998

Reputation: 1432

Use insert():

lst = [['001-008  I', 'I', 'Enfermedades infecciosas y parasitarias', 2018, 6.398],
       ['001-008  I', 'I', 'Enfermedades infecciosas y parasitarias', 2017, 6.819],
       ...]

for row in lst:
    row.insert(2, roman_to_int(row[1])) # changed here

Upvotes: 1

Related Questions