igraph选择通用属性的功能

时间:2015-07-02 18:27:27

标签: python igraph

我正在通过关注this tutorial来学习igraph

以下是我之前不熟悉的教程中的语法

# g is a Graph object
# g.vs are vertices of g
>>> g.vs.select(age_lt=30)
# this returns vertices which has "age" attribute less than 30

我需要更多通用

更具体地说,我想获得属性atr小于c的顶点。说,atrstringcint

我试过了:

>>> atr = 'age'
>>> c = 30
>>> g.vs.select(atr + '_lt'= c)

但是,我得到SyntaxError

  

SyntaxError:keyword不能是表达式

我不想手动执行,例如:

>>> [v for v in g.vs if v[atr] < c]

因为我的图表

2 个答案:

答案 0 :(得分:2)

你可以使用dict和str.format:

atr = 'age'
c = 30

g.vs(**{'{}_lt'.format(atr): c}

如果你担心记忆,你也可以使用gen exp:

(v for v in g.vs if v[atr] < c)

两者都返回相同的输出:

In [2]: g = Graph([(0,1), (0,2), (2,3), (3,4), (4,2), (2,5), (5,0), (6,3), (5,6)])

In [3]: g.vs["name"] = ["Alice", "Bob", "Claire", "Dennis", "Esther", "Frank", "George"]   
In [4]: g.vs["age"] = [25, 31, 18, 47, 22, 23, 50]   
In [5]: g.vs["gender"] = ["f", "m", "f", "m", "f", "m", "m"]   
In [6]: g.es["is_formal"] = [False, False, True, True, True, False, True, False, False]  
In [7]: atr = 'age'    
In [8]: c = 30    
In [9]: list(g.vs(**{'{}_lt'.format(atr): c}))
Out[9]: 
[igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,0,{'gender': 'f', 'age': 25, 'name': 'Alice'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,2,{'gender': 'f', 'age': 18, 'name': 'Claire'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,4,{'gender': 'f', 'age': 22, 'name': 'Esther'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,5,{'gender': 'm', 'age': 23, 'name': 'Frank'})]

In [10]: list(v for v in g.vs if v[atr] < c)
Out[10]: 
[igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,0,{'gender': 'f', 'age': 25, 'name': 'Alice'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,2,{'gender': 'f', 'age': 18, 'name': 'Claire'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,4,{'gender': 'f', 'age': 22, 'name': 'Esther'}),
 igraph.Vertex(<igraph.Graph object at 0x7f06ae24f810>,5,{'gender': 'm', 'age': 23, 'name': 'Frank'})]

你在gen exp上赢得了所有len等...但是如果你只是想要过滤的元素它似乎非常有效:

In [14]: timeit list(v for v in g.vs if v[atr] < c)
100000 loops, best of 3: 4.7 µs per loop

In [15]: timeit list(g.vs(**{'{}_lt'.format(atr): c}))
100000 loops, best of 3: 14.5 µs per loop

答案 1 :(得分:2)

When the first parameter to select is a callable,如果callable返回True,则选择顶点。

通过这种方式,您可以应用相对更复杂的查询。例如:

import igraph

G = igraph.Graph() 
G.add_vertex("John", age=22) 
G.add_vertex("Vilma", age=20) 
G.add_edge("John", "Vilma") 
vRes = G.vs.select(lambda x:x["name"]=="John" and x["age"]>20)
#Or, with query parameters as below
#someAttribute = "age"
#someValue = 20
#vRes = G.vs.select(lambda x:x[someAttribute] > someValue)

在上面的lambda中,参数x是igraph::Vertex,它提供对所有顶点属性的访问。

A similar interface存在以选择边缘。

希望这有帮助。