Reputation: 19
I need to create a list of a list of tuples from a text file. The file is like this:
[]
[(1, 4)]
[(1, 4), (2, 6)]
[(1, 4), (2, 16), (3, 4)]
[(1, 4), (2, 22), (3, 24), (4, 1)]
[(1, 4), (2, 32), (3, 48), (4, 16)]
[(1, 4), (2, 38), (3, 92), (4, 52), (5, 4)]
I need to extract each line into a list called combinations and be able to call the values inside the tuples like this:
combinations[1] // (1,4) <br>
combinations[1][1] // 4 <br>
I'm new to python, I can get each line into the list but they are of string type and a list of tuples
with open("combinations.txt", 'r') as f:
combinations = f.read().splitlines()
What I need:
combinations[1] // (1,4)
combinations[1][1] // 4
What I get:
combinations[1] // '[(1, 4)]'
Upvotes: 0
Views: 285
Reputation: 31349
Since these data structures can be read by python, you can do it with ast.literal_eval
:
import ast
with open('combinations.txt') as f:
tuples = list(map(ast.literal_eval, f))
Your tuples are now in the list tuples
.
Good luck!
Upvotes: 2