0
我嘗試使用arraylist來實現圖形,但是當我打印(graph.edges())爲什麼一些數據會顛倒{頂點,節點},它的意思是我不應該使用append?Python追加數據反轉
{node,vertex}
這個數據結構是無序的:
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())
謝謝!有沒有任何文件可以讓我參考? –
@RoyWu是的。使用[官方文檔](https://docs.python.org/3/library/stdtypes.html)。瞭解[sets here](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset)。 –