2

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.

3
  • 3
    Or ast.literal_eval depending on what A, B, C, ... look like. Commented Jan 28, 2013 at 20:06
  • Do you need this as output: [[('A','B'), ('B','C')],[('x','y'), ('z','v')]]? Or do you have values for A,B,C...? Commented Jan 28, 2013 at 20:10
  • Much better to avoid eval. I'd prefer using a parser(maybe even ast.parse, or, as mgilson proposed, ast.literal_eval if those letters represent literals). Commented Jan 28, 2013 at 20:11

4 Answers 4

3

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']]]
Sign up to request clarification or add additional context in comments.

Comments

1

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']]]

Comments

0

Once you've read the line from the file:

import ast

parsed_list = ast.literal_eval(line)

Comments

0

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')]]
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.