为什么igraph的add_vertices()不能处理一组字符串?

2024-04-25 09:10:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这无疑是由于我对Python缺乏了解。。。但为什么这对igraph无效呢?在

import igraph
g=igraph.Graph()
verts = {'1','2','3'}
g.add_vertices(verts)
for v in g.vs:
    print v

输出:

^{pr2}$

我本来希望得到以下输出(我用add_vertices(list(verts))得到):

igraph.Vertex(<igraph.Graph object at 0x106347af8>,0,{'name': '1'})
igraph.Vertex(<igraph.Graph object at 0x106347af8>,1,{'name': '3'})
igraph.Vertex(<igraph.Graph object at 0x106347af8>,2,{'name': '2'})

^{}上的文档说

add_vectirces(n)n - the number of vertices to be added, or the name of a single vertex to be added, or an iterable of strings, each corresponding to the name of a vertex to be added. Names will be assigned to the name vertex attribute.

我认为verts是一个有效的字符串iterable。我的错误在哪里?在


Tags: ofthetonameaddaddedobjectbe
1条回答
网友
1楼 · 发布于 2024-04-25 09:10:26

从图source

def add_vertices(self, n): 
     if isinstance(n, basestring):
          # some code
     elif hasattr(n, "__iter__"): 
          m = self.vcount() 
          if not hasattr(n, "__len__"): 
               names = list(n) 
          else: 
               names = n 
          result = GraphBase.add_vertices(self, len(names)) 
          self.vs[m:]["name"] = names # assignment is done here
          return result

将该顶点序列片段中每个顶点的name属性分配给names中的值似乎是合理的。如果这是在纯Python中完成的,它将简单地传递为解包,但Graph类子类是用c编写的GraphBase

所以行为只能用结果来描述。如果传递无序的iterablesetdict),顶点序列的每个属性都将iterable本身作为值,但是如果传递有序的iterable(比如tuplelist),则值是unpacked(不是python意义上的),并分配给vs的那一部分。在

您可以通过在以下位置重复代码段来确认:

^{pr2}$

以及

verts = {'1': 'one' ,'2': 'two', '3': 'three'} # unordered

但是frozensets?在

frozensets也是不可订阅的,因此C代码只需重复与set相同的行为。在

I thought verts was a valid iterable of strings

但对于Python中的索引无效。我想文件需要整容。在

相关问题 更多 >