Here is my text file, which consists of a tuple on each line:
(1, 2)
(3, 4)
(5, 6)
What's the most both rough and optimized perspective to read above file and generate a list like below structure:
[[1,2],[3,4],[5,6]]
Here is my current approach, is not which truly what I want:
with open("agentListFile.txt") as f:
agentList = [agentList.rstrip('\n') for line in f.readlines()]
You can use ast.literal_eval
to safely evaluate the tuple and convert those tuples into a list inside a list-comp, eg:
import ast
with open("agentListFile.txt") as f:
agent_list = [list(ast.literal_eval(line)) for line in f]
for more information, read the doc of ast.literal_eval
, and this thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With