2

假设我在文件中有这样的东西:

[[(A,B), (B,C)],[(x,y), (z,v)]]

我希望这是一个 python 列表列表。我怎么做?

最后,我希望能够遍历这个数组的行和列,并获取每对相邻的值来比较它们。

4

4 回答 4

3

更深奥的做法:

import yaml
from string import maketrans

s = "[[(A,B), (B,C)],[(x,y), (z,v)]]"    
yaml.load(s.translate(maketrans("()", "[]")))

出去:

[[['A', 'B'], ['B', 'C']], [['x', 'y'], ['z', 'v']]]
于 2013-01-28T20:47:10.230 回答
1

这有效:

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

如果您确实想要 LoLoL 而不是 LoLoT(如上所述),请执行以下操作:

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']]]
于 2013-01-28T21:15:00.997 回答
0

从文件中读取该行后:

import ast

parsed_list = ast.literal_eval(line)
于 2013-01-28T20:10:19.887 回答
0

纯蟒...

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

输出:

>>> 
[[(A,B), (B,C)],[(x,y), (z,v)]]
[[('A', 'B'), ('B', 'C')], [('x', 'y'), ('z', 'v')]]
>>> 
于 2013-01-28T20:30:12.920 回答