【发布时间】:2018-08-10 20:41:43
【问题描述】:
我有下面的网络图:
import networkx as nx
net = nx.Graph()
node_list = ["Gur","Qing","Samantha","Jorge","Lakshmi","Jack","John","Jill"]
edge_list = [("Gur","Qing",{"relation":"work"}),
("Gur","Jorge", {"relation":"family"}),
("Samantha","Qing", {"relation":"family"}),
("Jack","Qing", {"relation":"work"}),
("Jorge","Lakshmi", {"relation":"work"}),
("Jorge","Samantha",{"relation":"family"}),
("Samantha","John", {"relation":"family"}),
("Lakshmi","Jack", {"relation":"family"}),
("Jack","Jill", {"relation":"charity"}),
("Jill","John",{"relation":"family"})]
net.add_nodes_from(node_list)
net.add_edges_from(edge_list)
我想构建一个函数,给定网络、节点名称和关系类型,返回给定人员直接连接的人员列表。
这是我目前得到的功能:
def get_relations(graph,node,relationship):
if relationship == 'charity':
charity = [ (v) for (u,v,d) in net.edges( data = True) if d["relation"]=="charity"]
return list(set(charity))
else:
if relationship == 'work':
work = [ (v) for (u,v,d) in net.edges( data = True) if d["relation"]=="work"]
return list(set(work))
else:
if relationship == 'family':
family = [(v) for (u,v,d) in net.edges( data = True) if d["relation"]=="family"]
return list(set(family))
else:
return None
这样调用函数:
get_connections(net, 'John', 'family')
产生这个输出:
['Gur', 'Samantha', 'John', 'Lakshmi']
但这不是我需要的,我希望它只返回那些直接连接到 John 的人,或者无论节点是什么,使用直接路径,而不是间接路径。
以相同的方式调用函数应该会产生正确的输出:
['John', 'Jill', 'Samantha', 'Qing', 'Jorge', 'Gur']
代码尝试:
def get_relations(graph,node,relationship):
if relationship not in {'charity', 'work', 'family'}:
return None
relation_net = nx.Graph([(u,v,d) for (u, v, d) in net.edges( data = True)
if d["relation"] == relationship])
relation_subnet = nx.Graph([(node,v,d) for (u, v, d) in relation_net.edges( data = True)
if d["relation"] == relationship])
return list(set(relation_subnet.nodes))
但是,这仍然返回错误的结果。
【问题讨论】:
-
不是问题的原因,但您听说过
elif吗?如果没有,你应该检查一下。 -
请发帖minimal reproducible example。您的问题目前带有许多警告信号,表明显示的代码 sn-ps 并非全部来自您的代码的同一版本;看起来你可能试图从记忆中重新输入内容。
-
@xdze2 我需要获取所有与给定关系类型有连接的邻居,但只有那些与该关系类型连接的邻居,中间没有任何其他不同的关系类型。因此,例如,如果我有 John 和 Jill 与家庭关系直接相关,而 Jill 与任何其他有家庭关系的人有联系,我需要得到那个人的名字。但是,例如,如果 Jill 与一个人有工作关系,而那个人与另一个人有家庭关系,那我就不需要了。
-
@Miguel2488:是的。我将您的代码粘贴到一个文本文件中,连续运行五次,得到四个不同的集合作为输出。
-
@Miguel2488,我现在明白了。我认为混淆是因为“直接连接”对我来说意味着第一个邻居,即只有一个边缘可以遍历,这与边缘类型无关。图表很有趣也很让人头疼,尽情享受吧!也许这个很棒的课程会有所帮助youtube.com/watch?v=s-CYnVz-uh4
标签: python python-3.x graph networkx network-analysis