通用属性的 igraph select 函数

igraph select function for generic attributes

我正在学习 igraph,方法是关注 this tutorial

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

# 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 can't be an expression

我不想手动操作,例如:

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

因为我的图表很大

你可以使用字典和 str.format:

atr = 'age'
c = 30

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

如果你担心内存问题,你也可以使用 gen exp:

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

两者return相同的输出:

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

When the first parameter to select is a callable,如果可调用 returns True,则顶点被 selected。

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

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 存在到 select 条边。

希望这对您有所帮助。