0

I have some data like,

  1  2  3  4
  3  5  6  7
  2  8  9  10

and my code is

    #!/bin/usr/python
    file=open("fer.txt","r")
    M=[]
    P=[]
    K=[]
    def particle(M,P,K):
        for line in file:
            y=line.split()
            M.append(y)
        for i in range(3):
            for j in range(4):
                P.append(float(M[i][j]))
            K.append(P)
        return K
   print(particle(M,P,K))

and then I got

[[1.0, 2.0, 3.0, 4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0], [1.0, 
2.0, 3.0, 4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0], [1.0, 2.0, 3.0, 
4.0, 3.0, 5.0, 6.0, 7.0, 2.0, 8.0, 9.0, 10.0]]

but I ahould have or I want something like this,

[[1.0, 2.0, 3.0, 4.0,], [3.0, 5.0, 6.0, 7.0],[ 2.0, 8.0, 9.0, 10.0]]

Edit for duplicate flag: I dont see how its a duplicate question of mine. I am asking different thing also I am trying to understand why my code doesnt work.

Layla
  • 117
  • 2
  • 7
  • 7
    ...why is the title of the question asking about string->float conversion? That's the one part of your code that actually works correctly. – Aran-Fey Apr 25 '18 at 09:38
  • I couldnt convert them in a form that I wanted – Layla Apr 25 '18 at 09:41
  • I think your problem is that P is the same object every time you append it to K – abukaj Apr 25 '18 at 09:41
  • yes but why it acts like that I have a range of j 4 so that shouldnt have happened ? – Layla Apr 25 '18 at 09:43
  • With `K.append(P)` you append one and the same list instance to the matrix multiple times. The range has nothing to do with it. – Aran-Fey Apr 25 '18 at 09:58

2 Answers2

1

Using an iteration. You can use map to convert all elements of list to float.

Ex:

res = []
with open(filename2) as infile:
    for line in infile:
        line = line.strip()
        res.append(map(float, line.split()))
print(res)

Output:

[[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

first answer is correct but if you want in a one liner:


#sample.txt content: 
1  2  3  4
3  5  6  7
2  8  9  10

#code:

In [12]: d = open('sample.txt').readlines()
    ...: result =  [map(float, x.split()) for x in d]

output:

In [13]: result
Out[13]: [[1.0, 2.0, 3.0, 4.0], [3.0, 5.0, 6.0, 7.0], [2.0, 8.0, 9.0, 10.0]]
Community
  • 1
  • 1
Rachit kapadia
  • 705
  • 7
  • 18