0

I have a txt file which looks like this:

0.41,"[1.0, 0.0, 1.0]","[16.4, 0.0, 0.0]"    
0.23,"[0.0, 2.0, 2.0]","[32.8, 0.0, 0.0]"    
0.19,"[0.0, 0.0, 3.0]","[92.8, 0.0, 0.0]"   

and I hope to read it and convert the strings to lists:

a=[0.41, 0.23, 0.19, 0.03, 0.02, 0.02]    
b=[[1.0, 0.0, 1.0],[0.0, 2.0, 2.0],[0.0, 0.0, 3.0]]    
c=[[16.4, 0.0, 0.0],[32.8, 0.0, 0.0],[92.8, 0.0, 0.0]]     

How can I do this in python?

Thanks in advance,

Fei

2
  • Since you're new to SO let me mention that when you put a question here you should show us what code you have written to try to solve your own problem. Otherwise it appears that you are using the rest of us as a code writing service. Commented Feb 27, 2017 at 19:54
  • I don't think you can get a=[0.41, 0.23, 0.19, 0.03, 0.02, 0.02] with your sample input. It doesn't make sense. You can only have 3 values for each list or I'm lost in the logic. Commented Feb 27, 2017 at 19:55

1 Answer 1

2

I would use csv module to properly tokenize the items, then I'd transpose the rows using zip and convert the string data to python lists/values using ast.literal_eval

import csv
import ast


with open("file.txt") as f:
   cr = csv.reader(f)
   items = [[ast.literal_eval(x) for x in row] for row in zip(*cr)]

print(items)

result: a list of lists

[[0.41, 0.23, 0.19], [[1.0, 0.0, 1.0], [0.0, 2.0, 2.0], [0.0, 0.0, 3.0]], [[16.4, 0.0, 0.0], [32.8, 0.0, 0.0], [92.8, 0.0, 0.0]]]

That's not the general case, but if you know you exactly have 3 items in the list, you can unpack them to any variables you want:

if len(items)==3:
    a,b,c = items
    print(a)
    print(b)
    print(c)

and you get:

[0.41, 0.23, 0.19]
[[1.0, 0.0, 1.0], [0.0, 2.0, 2.0], [0.0, 0.0, 3.0]]
[[16.4, 0.0, 0.0], [32.8, 0.0, 0.0], [92.8, 0.0, 0.0]]

note that your expected input is not possible for a given the input data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.