我还在学习使用对象。我将vertices()定义为在Graph中返回顶点(初始化为vs)的方法。我知道有一种更简洁,更优雅的方式来编写顶点(),但究竟是如何逃避我的。
具体而言,这涉及Think Complexity中的练习2.5:http://greenteapress.com/complexity/html/book003.html#toc12
class Graph(dict):
def __init__(self, vs=[], es=[]):
for v in vs:
self.add_vertex(v)
def add_vertex(self, v):
"""Add a vertex to the graph."""
self[v] = {}
def vertices(self):
v = []
for i in range(len(self)):
v.append(i)
return v
答案 0 :(得分:1)
你可以使用列表推导使其成为一行:
def vertices(self):
return [i for i in range(len(self))]
答案 1 :(得分:1)
我将vertices()定义为返回顶点的方法(初始化) 在图中作为vs。
由于vs
中的__init__
包含字典的键,我想这就是你想要的。
def vertices(self):
return self.keys()
如果是这样,您根本不需要vertices
方法 - 只需始终使用Graph.keys()