-1

I am loading data from a file and want it to be stored in a matrix. I am looking to read the data in as a float rather than a string. How do I do this?

with open("hw2_data.txt", "r") as dataFile: 
    X = [line.split() for line in dataFile]

I have tried various things with float() but cannot seem to figure it out.

  • 1
    see [this](https://stackoverflow.com/a/1614247/6505847) – AzyCrw4282 Mar 06 '20 at 01:24
  • Please share what you’ve tried. Have you done any research? Also, variable and function names should generally follow the `lower_case_with_underscores` style. – AMC Mar 06 '20 at 03:00

1 Answers1

2

Use a nested listcomp or map to do this:

X = [[float(x) for x in line.split()] for line in dataFile]

or:

X = [[*map(float, line.split())] for line in dataFile]

[*map(...)] is just the unpacking way of spelling list(map(...)); you can use either on any supported version of Python 3.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271