-2

I would like to retrieve a set of data in a file in the form of a list.

The following is the data i am reading from the file which I want to add to list:

file input: (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)

The following code shows what I have now:

with open("partial.txt") as f:
List = f.read().splitlines()

graph1 = ','.join('({0})'.format(w) for w in List)

print (graph1)

The output I get is:

>> (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)

BUT I want the above result in [ ], like this:

>> [(3,5),(5,2),(2,1),(4,2),(4,1),(3,1)]

Can someone show what I need to do to get the above result

Community
  • 1
  • 1
user3624406
  • 29
  • 1
  • 7

2 Answers2

3
import ast

s = "(3,5),(5,2),(2,1),(4,2),(4,1),(3,1)"

>>> list(ast.literal_eval(s))
[(3, 5), (5, 2), (2, 1), (4, 2), (4, 1), (3, 1)]

Here is an SO link to eval vs ast.literal_eval

Community
  • 1
  • 1
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • I did this and I get: [((3, 5), (5, 2), (2, 1), (4, 2), (4, 1), (3, 1))]. Why is there extra ( ) ? – user3624406 Aug 26 '16 at 07:27
  • Better to use [`ast.literal_eval()`](https://docs.python.org/2/library/ast.html#ast.literal_eval). The output for this string is the same, but `ast.literal_eval()` won't actually hand out the keys to the process to any comer the way `eval()` does. – Martijn Pieters Aug 26 '16 at 07:29
  • @user3624406: sounds like you did `[eval(s)]` instead. – Martijn Pieters Aug 26 '16 at 07:29
0

Solved it by this code, list of tuples! :

with open('partial.txt') as f:
graph = [tuple(map(int, i.split(','))) for i in f]

print (graph)
user3624406
  • 29
  • 1
  • 7