Python追加数据反向

时间:2016-09-22 06:32:22

标签: python python-3.5

我尝试使用arraylist来实现图形但是当我打印(graph.edges())为什么有些数据会反转{vertex,node}时,它的意思是我应该使用append?

class Graph(object):

def __init__(self, graph_dict=None):
    """ initializes a graph object
                If no dictionary or None is given,
                an empty dictionary will be used
    """
    if graph_dict == None:
        graph_dict = {}
    self.__graph_dict = graph_dict

def vertices(self):
    """ returns the vertices of a graph """
    return list(self.__graph_dict.keys())

def edges(self):
    """ returns the edges of a graph """
    return self.__generate_edges()

def __generate_edges(self):
    edges = []
    for vertex in self.__graph_dict:
        for node in self.__graph_dict[vertex]:
            if {node, vertex} not in edges:
                edges.append({vertex,node})
    return edges


if __name__ == '__main__':
x = {'10': ['80558', '192929', '266485', '500235', '504757'], '4': ['16050', '286286', '310803', '320519', '408108', '448284'], '20': ['23251', '25337', '61306', '186932', '218984', '412652', '450610', '476125'], '11': ['57761', '107436', '400957', '512424'], '15': ['67084', '85444', '252980', '422732', '425706', '428290'], '2': ['27133', '62291', '170507', '299250', '326776', '331042', '411179', '451149', '454888'], '8': ['10758', '55461', '60605', '148586', '184847', '242156', '445607', '453513'], '1': ['88160', '118052', '161555', '244916', '346495', '444232', '447165', '500600'], '6': ['162248', '298989', '398542', '495077'], '16': ['128935', '148997', '422237'], '17': ['18919', '309780'], '18': ['41174', '45026', '168895'], '7': ['30028', '47672', '355935'], '19': ['203677'], '12': ['386032'], '5': ['173362', '305321', '407216', '489756']}

graph = Graph(x)
print("Vertices of graph:")
print(graph.vertices())

print("Edges of graph:")
print(graph.edges())

1 个答案:

答案 0 :(得分:1)

使用此表示法时使用set

{node,vertex}

此数据结构无序。尝试使用元组:

(node, vertex)