简体   繁体   中英

How do I find the number of vertices in a graph created by iGraph in python?

I'm writing a function that receives a graph as input. The very first thing I need to do is determine the order of the graph (that is, the number of vertices in the graph).

I mean, I could use g.summary() (which returns a string that includes the number of vertices), but then I'd have parse the string to get at the number of vertices -- and that's just nasty.

To get the number of edges I'm using len(g.get_edgelist()) , which works. But there is no g.get_vertexlist() , so I can't use the same method.

Surely there is an easy way to do this that doesn't involve parsing strings.

g.vcount() is a dedicated function in igraph that returns the number of vertices. Similarly, g.ecount() returns the number of edges, and it is way faster than len(g.get_edgelist()) as it does not have to construct the full edge list in advance.

As some functions in igraph have been renamed in meantime, I found the answers here out of date. What the docs suggest now is calling

gorder(g)

which works for me. Analogy for ecount is

gsize(g)   # vcount(g) still works, but not g.vcount()

It's useful to note that help pages are cleverly redirected, so

?vcount

brings you to gorder docs etc.

g.vs should return the sequence of vertices as an igraph.VertexSeq object:

>>> from igraph import Graph
>>> g = Graph.Formula("A-B")
>>> g.vs["name"]
['A', 'B']
>>> len(g.vs)
2
>>> g.vcount()
2

Edit: As @Tamas mentions below, g.vcount() will also return the number of vertices. Example edited to account for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM