如何将成对列表转换成字典,并将每个元素作为成对值列表的键?

时间:2019-03-29 17:33:02

标签: python list dictionary type-conversion

我正在做涉及图形的课程。我有边列表E = [(('a','b'),('a','c'),('a','d'),('b','c')等)和我想要一个函数以字典{'a':['b','c','d'],'b':['a'等)的形式将它们转换为邻接矩阵,这样我可以使用仅输入这些词典的功能。

我的主要问题是我无法弄清楚如何使用循环来添加key:values而不只是覆盖列表。我的函数的先前版本会输出[]作为所有值,因为'f'没有连接。

我已经尝试过了:

V = ['a','b','c','d','e','f']
E=[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

def EdgeListtoAdjMat(V,E):
    GA={}
    conneclist=[]
    for v in V:
        for i in range(len(V)):
            conneclist.append([])
            if (v,V[i]) in E:
                conneclist[i].append(V[i])
    for i in range(len(V)):
        GA[V[i]]=conneclist[i]
    return(GA)

EdgeListtoAdjMat(V,E)输出:

{'a': [], 'b': ['b'], 'c': ['c', 'c'], 'd': ['d', 'd', 'd'], 'e': [], 'f': []}

它应该输出:

{'a':['b','c','d'],
'b':['a','c','d'],
'c':['a','b','d'],
'd':['a','b','c'],
'e':[],
'f':[]
}

6 个答案:

答案 0 :(得分:0)

您想要实现的逻辑实际上很简单:

V = ['a','b','c','d','e','f']
E=[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

result = {}
for elem in V:
     tempList = []
     for item in E:
          if elem in item:
               if elem == item[0]:
                    tempList.append(item[1])
               else:
                    tempList.append(item[0])
     result[elem] = tempList
     tempList = []

print(result)

结果:

{'a': ['b', 'c', 'd'], 'b': ['a', 'c', 'd'], 'c': ['a', 'b', 'd'], 'd': ['a', 'b', 'c'], 'e': [], 'f': []}

对于V中的每个元素,执行检查以查看该元素是否存在于E中的任何元组中。如果存在,则将在该元组上组成一对的元素并追加到临时列表中。检查E中的每个元素之后,更新result字典并移至V的下一个元素,直到完成。

要返回您的代码,您需要对其进行如下修改:

def EdgeListtoAdjMat(V,E):
    GA={}
    conneclist=[]
    for i in range(len(V)):
        for j in range(len(V)):
            # Checking if a pair of two different elements exists in either format inside E. 
            if not i==j and ((V[i],V[j]) in E or (V[j],V[i]) in E):
                conneclist.append(V[j])
        GA[V[i]]=conneclist
        conneclist = []
    return(GA)

答案 1 :(得分:0)

一种更有效的方法是遍历边缘并将两个方向的顶点附加到列表的输出字典。使用dict.setdefault用列表初始化每个新密钥。并且当边缘上的迭代完成时,遍历输出字典中尚未存在的其余顶点,以将空列表分配给它们:

def EdgeListtoAdjMat(V,E):
    GA = {}
    for a, b in E:
        GA.setdefault(a, []).append(b)
        GA.setdefault(b, []).append(a)
    for v in V:
        if v not in GA:
            GA[v] = []
    return GA

所以给定:

V = ['a', 'b', 'c', 'd', 'e', 'f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

EdgeListtoAdjMat(V, E))将返回:

{'a': ['b', 'c', 'd'], 'b': ['a', 'c', 'd'], 'c': ['a', 'b', 'd'], 'd': ['a', 'b', 'c'], 'e': [], 'f': []}

答案 2 :(得分:0)

由于您已经在V中拥有了顶点列表,因此很容易准备带有空连接列表的字典。然后,只需遍历边缘列表并添加到两侧的数组中即可:

V = ['a','b','c','d','e','f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

GA = {v:[] for v in V}
for v1,v2 in E:
    GA[v1].append(v2)
    GA[v2].append(v1)

答案 3 :(得分:0)

我认为您的代码不是python风格的代码,因为您使用的是python的内置库和numpy的索引,因此您可以编写更具可读性的代码,调试起来更简单,而且速度更快。

def EdgeListToAdjMat(V, E):
    AdjMat = np.zeros((len(V), len(V)))  # the shape of Adjancy Matrix
    connectlist = {
        # Mapping each character to its index
        x: idx for idx, x in enumerate(V)
    }
    for e in E:
        v1, v2 = e
        idx_1, idx_2 = connectlist[v1], connectlist[v2]
        AdjMat[idx_1, idx_2] = 1     
        AdjMat[idx_2, idx_1] = 1

    return AdjMat

答案 4 :(得分:0)

如果您考虑使用库,则networkx专门用于以下类型的网络问题:

import networkx as nx 

V = ['a','b','c','d','e','f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

G=nx.Graph(E)
G.add_nodes_from(V)
GA = nx.to_dict_of_lists(G)

print(GA)

# {'a': ['c', 'b', 'd'], 'c': ['a', 'b', 'd'], 'b': ['a', 'c', 'd'], 'e': [], 'd': ['a', 'c', 'b'], 'f': []}

答案 5 :(得分:0)

您可以使用itertools.groupby

将边列表转换为地图
from itertools import groupby
from operator import itemgetter

V = ['a','b','c','d','e','f']
E = [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

# add edge in the other direction. E.g., for a -> b, add b -> a
nondirected_edges = E + [tuple(reversed(pair)) for pair in E]

# extract start and end vertices from an edge
v_start = itemgetter(0)
v_end = itemgetter(1)

# group edges by their starting vertex
groups = groupby(sorted(nondirected_edges), key=v_start)
# make a map from each vertex -> adjacent vertices
mapping = {vertex: list(map(v_end, edges)) for vertex, edges in groups}

# if you don't need all the vertices to be present
# and just want to be able to lookup the connected
# list of vertices to a given vertex at some point
# you can use a defaultdict:
from collections import defaultdict
adj_matrix = defaultdict(list, mapping)

# if you need all vertices present immediately:
adj_matrix = dict(mapping)
adj_matrix.update({vertex: [] for vertex in V if vertex not in mapping})