0

I have the following string mydata that in fact is an embedded list of lists:

 u'[[[1.7594271439650333, 41.82815539277221], [1.7594360823099031,41.82815010753548], [1.7594365489105126,41.828102229437455], [1.75943006926896,41.82809815273617], [1.7593938715967752,41.8280981826361], [1.75938821767524, 41.828104309113314], [1.759388051589258, 41.8281507714983], [1.7594271439650333, 41.82815539277221]]]

I want to convert it to a list of tuples as follows:

mytuple = [tuple(l) for l in mydata[0]]

But it does not work since mydata is indeed a string.

kabanus
  • 24,623
  • 6
  • 41
  • 74
Markus
  • 3,562
  • 12
  • 48
  • 85
  • 1
    What is the source of this string? Where does it come from? Is it defined to be JSON? In that cases, you should use the json module to parse it. If it is some other format, you should use that. – zvone Sep 09 '18 at 12:16
  • No, it's a column of the DataFrame. If I could change the source, I would do it. – Markus Sep 09 '18 at 12:17
  • But someone put the string there. Did they document the format? Did they use json to create the string, or did they uses python's `str(list_of_lists)` to create the string? – zvone Sep 09 '18 at 12:19
  • BTW, not that it matters, but how come you have a unicode string representation with `u` prefix (`u'[[...'`), characteristic to Python 2, and the question is tagged as Python 3? – zvone Sep 09 '18 at 12:20

1 Answers1

3

Since the string is a list literal, you can use ast.literal_eval, from the documentation:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.

import ast

a = u'[[[1.7594271439650333, 41.82815539277221], [1.7594360823099031, 41.82815010753548], [1.7594365489105126, 41.828102229437455], [1.75943006926896, 41.82809815273617], [1.7593938715967752, 41.8280981826361], [1.75938821767524, 41.828104309113314], [1.759388051589258, 41.8281507714983], [1.7594271439650333, 41.82815539277221]]]'
mydata = ast.literal_eval(a)
mytuple = [tuple(l) for l in mydata[0]]

print(mytuple)

Output

[(1.7594271439650333, 41.82815539277221), (1.7594360823099031, 41.82815010753548), (1.7594365489105126, 41.828102229437455), (1.75943006926896, 41.82809815273617), (1.7593938715967752, 41.8280981826361), (1.75938821767524, 41.828104309113314), (1.759388051589258, 41.8281507714983), (1.7594271439650333, 41.82815539277221)]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76