Lee*_*aan 5 python networkx python-3.x
我用 networkx 创建了一个图,每个节点都有一些属性。所以我想搜索所有节点的特定属性,并将每个具有此属性的节点保存在列表中。我编写了以下代码,但出现错误:
for node in G.nodes():
for attribute in G.node[node]['attributes']:
if attribute in question:
setOfUsers.append(node)
Run Code Online (Sandbox Code Playgroud)
使用此代码,我收到以下错误:
for attribute in G.node[node]['attributes']:
KeyError: 'attributes'
Run Code Online (Sandbox Code Playgroud)
所以我搜索了论坛,并尝试了一些不同的方法来解决问题:
for node, data in G.nodes(data=True):
if data['attributes'] == question[0]:
setOfUsers.append(node)
Run Code Online (Sandbox Code Playgroud)
但我有同样的错误。如何遍历属性?
更新:我使用下面的代码添加节点属性。我从文件中读取属性,拆分逗号和换行符,然后将列表保存在节点中
for line in file2:
line = line.strip()
words = line.split('\t')
node = int(words[0])
attributes= words[1]
splittedAttributes = attributes.split(',')
if node in G.nodes():
G.node[node]['attributes'] = splittedAttributes
Run Code Online (Sandbox Code Playgroud)
小智 7
您确定之前已将信息添加到节点吗?看起来 networkX 对你的“属性”一无所知。通过添加信息我的意思是这样的:
for node in G.nodes():
G.node[node]['attributes']= attributes[node]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用你自己的代码来检查它们
for node in G.nodes():
for attribute in G.node[node]['attributes']:
if attribute in question:
setOfUsers.append(node)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3810 次 |
| 最近记录: |