I have a structured list of lists in which each element is a string. I want to convert certain (known index, always the same) elements in this list of lists to integers. I've tried using list comprehension or the isdigit()
method (there are no negative elements) but can't figure it out.
list_of_lists = [['spam','1','toast'], ['bacon','5','eggs'], ['juice', '8', 'tea']]
new_breakfast_list = [[int(element) for element in row] for row in list_of_lists]
The above code understandably gives ValueError: invalid literal for int() with base 10: 'spam'
when it tries converting the first element. I want to either ignore the error and move forward to the next element or maybe specifically loop over something like list_of_lists[i][1]
so I can get:
print(new_breakfast_list)
[['spam', 1, 'toast'], ['bacon', 5, 'eggs'], ['juice', 8, 'tea']]