I'm new to python and I need to create a list of lists (a matrix) of float values from a list of strings. So if my input is:
objectListData = ["1, 2, 3, 4", "5, 6, 7, 8", "9, 0, 0, 7", "5, 4, 3, 2", "2, 3, 3, 3", "2, 2, 3, 3"]
what I want to obtain is:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 7], [5, 4, 3, 2], [2, 3, 3, 3], [2, 2, 3, 3]]
Here's my code:
objectListData = ["1, 2, 3, 4", "5, 6, 7, 8", "9, 0, 0, 7", "5, 4, 3, 2", "2, 3, 3, 3", "2, 2, 3, 3"]
objectListDataFloats = [[0] * len(objectListData[0].split(', '))] * len(objectListData)
for count in range(1,len(objectListData)):
for ii in range(1,len(objectListData[count].split(', '))):
objectListDataFloats[count][ii] = float(objectListData[count].split(', ')[ii])
print objectListDataFloats
objectListDataFloats=[[0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0]]
where is the error? I can't find it. Thanks
for i in range(len(foo)), you're probably doing it wrong. If you just want each value infoo, just dofor value in foo. If you need the index as well as the value, dofor index, value in enumerate(foo). Either way, you completely avoid the potential for off-by-one errors (like the one you actually have in your code), and make everything simpler and more readable.