0

I am opening a text file and appending the index[1] of it to a list, with the output being ['18.0', '15', '8.50', '10.50']. My desired output is [18, 15, 8.5, 10.5].

file = open(file, "r")
sheet = sheet = [line.strip() for line in theFile]
del sheet[0]
sheet.sort()
for i in sheet:
    lines = (i.split(','))
    list.append(lines[1]) 

2 Answers2

1

map solves your problem pretty easily.

newList = list(map(float, myList))

The map function will apply a function (in this case, float) to every value in a list. It returns a map object, which we need to convert to a list. That's what list() at the beginning of the line does.

So, in your case, it should be something like:

lines = list(map(float, lines))

which will convert all ints in the list lines to floats.

rappatic
  • 71
  • 1
  • 3
  • 15
0

The easiest fix is to parse the floating point values as you append them to the list:

list.append(float(lines[1]))
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268