python - 给定列表创建无向图

标签 python python-3.x

我有一个列表:

entry=['A','B','C','null','B','A','D','null','E','F']

彼此相邻的字母(顶点)形成一条边。 'null' 是分隔符。

每条边的权重为 1。边 (A,B) 的权重为 2,因为它出现了两次。

为了形象化,上面的列表将是这个图表: enter image description here

我想创建一个字典,类似于邻接表。

dict= {
'A':{'B':2,'D',1},
'B':{'A':2,'C':1},
'C':{'B':1},
'D':{'A':1},
'E':{'F':1},
'F':{'E':1}
}

第一个键是顶点,第二个键是相邻顶点及其权重值。

如何得出上图。如果有任何其他更好的方式来表示上图,我将不胜感激。

最佳答案

一个解决方案是 reduce您的 entry 列表作为 reduce(没有累加器)一次查看 2 个相邻元素:

from functools import reduce

graph = {}

def add_edge(u, v):
    if u != 'null' and v != 'null':
        if u in graph:
            graph[u][v] = graph[u].get(v, 0) + 1
        else:
            graph[u] = {v: 1}
        if v in graph:
            graph[v][u] = graph[v].get(u, 0) + 1
        else:
            graph[v] = {u: 1}
    return v

entry = ['A','B','C','null','B','A','D','null','E','F']
reduce(add_edge, entry)

print(graph)
# {'B': {'A': 2, 'C': 1}, 'E': {'F': 1}, 'F': {'E': 1}, 'C': {'B': 1}, 'A': {'B': 2, 'D': 1}, 'D': {'A': 1}}

编辑:

一种“更纯粹”的归约方式是将相邻元素压缩在一起,然后使用初始化器归约:

def add_edge(graph, edges):
    u, v = edges
    if u != 'null' and v != 'null':
        # ... same thing as before
    return graph

entry = ['A','B','C','null','B','A','D','null','E','F']
graph = reduce(add_edge, zip(entry[:-1], entry[1:]), {})

关于python - 给定列表创建无向图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146355/

相关文章:

python - 根据HSV图像的值 channel 为图像创建条件掩模

python-3.x - 齿轮 discord.py 中的 @bot.event

python - 如何在 python 3.4 中预处理 yaml 文件?

python - 通过Python或Node访问GKE kubectl

python - 如何为每个列名添加后缀(或前缀)?

c++ - 如何在客户端 - 服务器应用程序中同步客户端和服务器端的相同对象?小消息框架适合这项工作吗?

performance - 有效地将逗号分隔值字符串转换为字节

python - Django中同一模型的多个多对多关系

python,可能是马尔可夫链的变体?

python - 从pdf转换为文本: lines and words are broken