1

I've looked at other examples (like this for example Getting a map() to return a list in Python 3.x) and I haven't been able to figure it out. I'm trying to turn a list like this (it's about a thousand lines but I'm making it short for here)

xyz = [' 0.35587716 -2.11974747 -3.69604539',
       ' 0.32428861 -2.15566737 -3.61313426',
       ' 0.35329223 -2.19372613 -3.75673156']

Into either an array or list of floats like this

b = [[0.35587716, -2.11974747, -3.69604539],
     [0.32428861, -2.15566737, -3.61313426],
     [0.35329223, -2.19372613, -3.75673156]]

I have tried the following

b = np.array(map(lambda x: map(int, x.split()), xyz))
b = [[int(y) for y in x.split()] for x in xyz]

with open("file.log") as f:
    lis=[map(int,line.split()) for line in f]

And all of these give me back something like:

<map object at 0x117a89390>
<map object at 0x117a89390>
<map object at 0x117a89390>

etc, etc.

But I don't know how to access the values in the map object. I'm using Python 3.6.0. I'm not sure what to do :(

ddog
  • 39
  • 5
  • I looked at other examples and none of them have worked so far. – ddog Jun 22 '18 at 23:49
  • If you're already using `numpy` I would suggest you simply transform you array of sting into an array of float and use the `reshape` or `resize` methods to get a matrix. Easier and faster. – domochevski Jun 23 '18 at 00:17
  • @ddog Why do you use `int` when you need `float`? I just tried `map(lambda x: map(float, x.split()), xyz)` and it outputs `[[0.35587716, -2.11974747, -3.69604539], [0.32428861, -2.15566737, -3.61313426], [0.35329223, -2.19372613, -3.75673156]]` just fine. – blhsing Jun 23 '18 at 00:18
  • @blhsing When I try `map(lambda x: map(float, x.split()), xyz)` I still get "". I'm not sure what the deal is :/ – ddog Jun 23 '18 at 00:33
  • @ddog Try casting it to `list` then: `list(map(lambda x: map(float, x.split()), xyz))` – blhsing Jun 23 '18 at 00:36
  • @blhsing that still returned . – ddog Jun 23 '18 at 00:39
  • @domochevski when i try to convert it to a float array I get an error like this "ValueError: could not convert string to float: ' 0.35587716 -2.11974747 -3.69604539'" -- I think it's because there are spaces. – ddog Jun 23 '18 at 00:44
  • @ddog Then just iterate over it. Try `for i in map(lambda x: map(float, x.split()), xyz): print(i)` – blhsing Jun 23 '18 at 00:51
  • @blhsing it still returns the same thing :/ – ddog Jun 23 '18 at 01:01
  • @ddog in python 3 the following gives you a 1D array: `a=np.array([float(x) for s in xyz for x in s.split()])` from here you only need to use `a.resize(3,3)` to get the matrix. – domochevski Jun 23 '18 at 01:11
  • @domochevski It works! Thank you so much for the help, I really appreciate it. I've been trying to figure this out for a few days now :) – ddog Jun 23 '18 at 05:36

0 Answers0