Let's say I have something like this in a file:
[[(A,B), (B,C)],[(x,y), (z,v)]]
I want this as a python list of lists. How do I do that?
In the end, I would like to be able to iterate through the rows and the columns of this array, and get each pair of adjacent values to compare them.
4 Answers 4
More esoteric way of doing it:
import yaml
from string import maketrans
s = "[[(A,B), (B,C)],[(x,y), (z,v)]]"
yaml.load(s.translate(maketrans("()", "[]")))
out:
[[['A', 'B'], ['B', 'C']], [['x', 'y'], ['z', 'v']]]
answered Jan 28, 2013 at 20:47
root
81.2k25 gold badges111 silver badges120 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This works:
>>> import re,ast
>>> st='[[(A,BC), (B,C)],[(x,y), (z,v)]]'
>>> ast.literal_eval(re.sub(r'(\w+)',r"'1円'",st))
[[('A', 'BC'), ('B', 'C')], [('x', 'y'), ('z', 'v')]]
If you really do want a LoLoL rather than a LoLoT (as above), do this:
def rep(match):
if match.group(1)=='(': return '['
if match.group(1)==')': return ']'
return "'{}'".format(match.group(1))
st='[[(A,B), (B,C)],[(x,y), (z,v)]]'
st=re.sub(r'(\w+|[\(\)])', rep,st)
>>> ast.literal_eval(st)
[[['A', 'B'], ['B', 'C']], [['x', 'y'], ['z', 'v']]]
answered Jan 28, 2013 at 21:15
dawg
105k24 gold badges143 silver badges217 bronze badges
Comments
Once you've read the line from the file:
import ast
parsed_list = ast.literal_eval(line)
answered Jan 28, 2013 at 20:10
ACEfanatic02
7045 silver badges13 bronze badges
Comments
Pure python...
s = "[[(A,B), (B,C)],[(x,y), (z,v)]]"
print s
s = filter(None, s[1:-1].replace(",[", "").replace("[", "").replace(" ", "").split(']'))
for i,t in enumerate(s):
t = filter(None, t.replace(",(", "").replace("(", "").split(')'))
t = [tuple(x.split(",")) for x in t]
s[i] = t
print s
Output:
>>>
[[(A,B), (B,C)],[(x,y), (z,v)]]
[[('A', 'B'), ('B', 'C')], [('x', 'y'), ('z', 'v')]]
>>>
answered Jan 28, 2013 at 20:30
ATOzTOA
36.1k23 gold badges101 silver badges119 bronze badges
Comments
lang-py
ast.literal_evaldepending on whatA,B,C, ... look like.[[('A','B'), ('B','C')],[('x','y'), ('z','v')]]? Or do you have values for A,B,C...?eval. I'd prefer using a parser(maybe evenast.parse, or, as mgilson proposed,ast.literal_evalif those letters represent literals).