1

I have tried to find this answer, but can only find it in pieces which I'm having trouble putting together.

Assume I have:

aList = [["Monday", "2.03","4.03"],["Tuesday","4.03","5.03"],["Wednesday","3.2","4.3"]]

I would like to iterate over this nested list and change the numbered string values to floats.

2 Answers 2

8
aList = [["Monday", "2.03","4.03"],
         ["Tuesday","4.03","5.03"],
         ["Wednesday","3.2","4.3"]]

def helper(s):
    try: return float(s)
    except ValueError: return s

aList[:] = [[helper(item) for item in subl] for subl in aList]
print aList

out:

[['Monday', 2.03, 4.03], ['Tuesday', 4.03, 5.03], ['Wednesday', 3.2, 4.3]]
Sign up to request clarification or add additional context in comments.

Comments

1
for item in aList:
    item[1] = float(item[1])
    item[2] = float(item[2])

1 Comment

This ans is simpler and more pythonic. Of course if we sure in data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.