Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of tuples to a raw list in a more optimized manner

Tags:

python

file

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()]
like image 550
User Avatar asked Feb 10 '23 03:02

User


1 Answers

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.

like image 160
Jon Clements Avatar answered Feb 13 '23 11:02

Jon Clements