2016-01-21 81 views
0

我是python语言的新手,已经使用networkx包。基本上我有一个客户和生产者的列表,并希望一个函数检索基于这些类型的当前列表的列表。networkx和迭代列表 - 我无法理解的一段代码

下面是检索客户功能的相关代码:

def customers_iter(self, data=False): 

    """ Return an iterator over all customers. 

     If the network is changed during iteration, the iterator becomes 
     invalid. 

     Parameters 
     ----------- 

     data - if True, return a list of (name, attributes) pairs, such 
       that attributes == net.node[name]. Otherwise, 
       only a list of customer names is returned. Default is 
       False. 
    """ 

    if data: 
     return (n for n in self.nodes_iter(data=True) 
        if self.node[n[0]]["type"] == "customer") 
    else: 
     return (n for n in self.nodes_iter() 
        if self.node[n]["type"] == "customer") 

我的问题是关于具体的如果 - 和else语句。首先检查第一个节点n [0]有什么意义? else-section中的语句是不是定义完全一样的东西?

问候, jazy

回答

0

根据该文档注释:

data - if True, return a list of (name, attributes) pairs, such 
     that attributes == net.node[name]. Otherwise, 
     only a list of customer names is returned. Default is 
     False. 

假设,即data参数具有在self.node_iter功能的相同的含义,第一分支(if)应该过滤对(name, attributes) ,但第二个(else)应该只筛选name s。

假设,也即self.node是用于保持缔合对name字典状结构 - >node,很容易看到,在第一分支,我们必须检索来自tuplename(这是n[0]) ,而在第二个分支中,我们可以使用n作为节点名称。

+0

非常感谢!我现在明白了:) – jazy

+0

您随时欢迎!为了帮助面临同样问题的人们,可以随意标记答案。 – soon