문제 설명
그래프를 통해 그래프 노드인 클래스 인스턴스의 속성에 액세스하는 방법은 무엇입니까? (How to access attributes of a class instance which is a graph node via the graph?)
클래스 정의:
class Blah:
def __init__(self,x):
self.x = x
main()의 일부: (가져온 networkx)
G = networkx.Graph()
H = []
for i in range(1,5):
H.append(Blah(i))
for i in H:
G.add_node(i)
이제 H[2].x
를 인쇄하려면 code> G를 사용하는 경우 어떻게 해야 하나요?
G[2].x
는 확실히 작동하지 않습니다. G(H[2]).x
가 작동합니까?
정보를 요청하기만 하면 됩니다. 내 문제에서 H를 사용할 수 있습니다.
참조 솔루션
방법 1:
you can access the node data as shown below
print(list(G.nodes())[1].x)
방법 2:
So if you define:
class Blah:
def __init__(self,x):
self.x = x
G = networkx.Graph()
H = []
for i in range(1,5):
H.append(Blah(i))
for i in H:
G.add_node(i)
Now you want to access the attributes of nodes of G. To do that, you need to use the networkx commands to access the nodes of G:
for node in G:
print(node.x)
> 1
> 2
> 3
> 4
(by Hitanshu Sachania、Ashok Kummar、Joel)