Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: Format a list within a list using for loops

Input:

data = [['A', 'B', 'C'], ['001', 'ddd', 'eee', '10'], ['002', 'fff', 'ggg', '20']]

Expected output:

data = ['A', 'B', 'C'], [1, 'ddd', 'eee', 10], [2, 'fff', 'ggg', 20]]
  • Convert columns with numerical values from strings to integers (with quotes around the numbers removed

I have attempted with the below code but I am getting this error:

ValueError: could not convert string to float: A

Could anyone point out my mistake?

formatted = []
for row in data:
    new_row = []
    for i, col in enumerate(row):
        if i != [1,2]:
            new_row.append(col)
            new_row.append(float(col))
    formatted.append(new_row)

print formatted
like image 226
doyz Avatar asked Mar 15 '26 20:03

doyz


1 Answers

The 'pythonic' way to do this is to try converting each element to an integer, and fall back to keeping the string in case of failure.

formatted = []
for row in data:
    new_row = []
    for elem in row:
        try:
            new_row.append(int(elem))
        except ValueError:
            new_row.append(elem)
    formatted.append(new_row)

print formatted
like image 76
Imran Avatar answered Mar 17 '26 10:03

Imran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!