在NetworkX“M努力实现以下目标:
- 一个图形中创建的母亲节点“和“儿童节点”,其中孩子节点仅具有1属性,母节点具有几个(4)。
- 创建母节点和子节点之间的边是否至少一个属性(键 - 值对)是相同的,
- 只有一个母节点和孩子节点之间创建一个优势:即使两个母节点具有4的一个重叠的属性,不应该有在两者之间的边缘
到目前为止,我有第一部分工作,并在第二个michaelg非常有帮助,但仍有一个错误。
import networkx as nx
from itertools import product
# Mother-nodes
M = [('E_%d' % h, {'a': i, 'b': j, 'c': k, 'd': l})
for h, (i, j, k, l) in enumerate(product(range(2), repeat=4), start=1)]
# children-nodes
a = [ ( 'a_%d' % i, {'a' : i}) for i in range(0,2) ]
b = [ ( 'b_%d' % i, {'b' : i}) for i in range(0,2) ]
c = [ ( 'c_%d' % i, {'c' : i}) for i in range(0,2) ]
d = [ ( 'd_%d' % i, {'d' : i}) for i in range(0,2) ]
# graph containing both
M_c = nx.Graph()
M_c.add_nodes_from(M)
ls_children = [a, b, c , d]
for ls_c in ls_children:
M_c.add_nodes_from(ls_c)
# what it looks like so far
list(M_c.nodes(data=True))[0:20]
[('E_9', {'a': 1, 'b': 0, 'c': 0, 'd': 0}),
('d_0', {'d': 0}),
('E_10', {'a': 1, 'b': 0, 'c': 0, 'd': 1}),
('b_0', {'b': 0}),
('E_2', {'a': 0, 'b': 0, 'c': 0, 'd': 1}),
('E_1', {'a': 0, 'b': 0, 'c': 0, 'd': 0}),
('c_1', {'c': 1}),
...
]
然后第二部分,其产生一个错误:
for start in M_c.nodes(data=True):
for end in M_c.nodes(data=True):
for attr in list(start[1].keys()):
if start[1][attr]:
if end[1][attr]:
if start[1][attr] == end[1][attr]:
M_c.add_edge(start[0], end[0] )
# Adding an else and continue statement does not affect the error,
# even adding three of them, for each if statement
# else:
# continue
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-32ae2a6095e5> in <module>()
3 for attr in list(start[1].keys()):
4 if start[1][attr]:
----> 5 if end[1][attr]:
6 if start[1][attr] == end[1][attr]:
7 M_c.add_edge(start[0], end[0] )
KeyError: 'a'
我也许忽视的东西 - 任何建议是极大的赞赏。
编辑-1:
正如ducminh建议我跑:
for mother_node in M:
for child_node in chain(a, b, c, d):
if child_node[1].items() <= mother_node[1].items():
M_c.add_edge(child_node, mother_node)
其返回此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-24f1a24a49e8> in <module>()
2 for child_node in chain(a, b, c, d):
3 if child_node[1].items() <= mother_node[1].items():
----> 4 M_c.add_edge(child_node, mother_node)
5
/usr/local/lib/python3.5/dist-packages/networkx/classes/graph.py in add_edge(self, u_of_edge, v_of_edge, **attr)
873 u, v = u_of_edge, v_of_edge
874 # add nodes
--> 875 if u not in self._node:
876 self._adj[u] = self.adjlist_inner_dict_factory()
877 self._node[u] = {}
TypeError: unhashable type: 'dict'