将字符串转换为包含集合的字典

时间:2014-05-15 05:07:51

标签: python

我的格式如下:

inp="({A,B,C},{(A,B),(B,C),(C,A)})"

{A,B,C}表示图表中的节点。

{(A,B),(B,C),(C,A)}代表连接的节点。

我想将此字符串转换为如下字典:

graph = {'A': set(['B','C']),
        'B': set(['C','A']),
        'C': set(['A','B'])}

set包含key节点所连接的节点。

A已与B相关联。 B已与CC is connected to A`。

相关联

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案

inp = "({A,B,C},{(A,C),(B,C),(C,A)})"
nodes,edges = inp[2:-2].split('},{')
nodes = nodes.split(',')
edges = [x.split(',') for x in edges[1:-1].split('),(')]
graph = dict([(node,set()) for node in nodes])
for edge in edges:
    graph[edge[0]].add(edge[1])
    graph[edge[1]].add(edge[0])
print graph

答案 1 :(得分:0)

正则表达式,lambda函数和列表理解拯救:

import re
inp="({A,B,C},{(A,B),(B,C),(C,A)})"

m = re.search("{(.*?)},{\((.*?)\)}",inp)

nodes = m.group(1).split(',')
edges = map(lambda x:x.split(','), m.group(2).split('),('))
graph = {}

for i in nodes:
 graph[i]=set([edge[edge.index(i)-1] for edge in edges if i in edge])

print graph

给出:

{'A': set(['C', 'B']), 'C': set(['A', 'B']), 'B': set(['A', 'C'])}

基于输入格式的模式匹配有点笨拙,但如果删除空格则可以使用。如果边缘具有多字符名称,它也可以完美地运行。

因为所有酷孩子似乎都是关于单列表推导的,所以这里有3行(如果排除输入,则为2行):

inp="({A,B,CC},{(A,B),(B,CC),(CC,A)})"
nodes,edges = inp[2:-3].split('},{(')
graph = dict([(i,set([edge[edge.index(i)-1] for edge in map(lambda x:x.split(','), edges.split('),(')) if i in edge])) for i in nodes.split(',')])

答案 2 :(得分:0)

一种离不开的方式:假装你的输入语法是python!

import ast
d = {}
_s1, s2 = (node for node in ast.walk(ast.parse(inp)) if isinstance(node, ast.Set))

for tup in s2.elts:
    n1,n2 = tup.elts
    d.setdefault(n1.id,set()).add(n2.id)
    d.setdefault(n2.id,set()).add(n1.id)

给出

d
Out[69]: {'A': set(['B', 'C']), 'B': set(['A', 'C']), 'C': set(['A', 'B'])}