【问题标题】:networkx and iteration of lists - piece of code I cannot understandnetworkx 和列表的迭代 - 我无法理解的一段代码
【发布时间】:2016-01-21 08:34:37
【问题描述】:

我是 python 语言的新手,一直在使用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")

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

问候, 杰西

【问题讨论】:

    标签: python list networkx


    【解决方案1】:

    根据文档注释:

    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)应该只过滤@ 987654327@s。

    同样假设 self.node 是一个类字典结构,用于保存关联对 name -> node,很容易看出,在第一个分支中,我们必须从tuple(即n[0]),而在第二个分支中,我们可以只使用n作为节点名称。

    【讨论】:

    • 非常感谢!我现在明白了:)
    • 随时欢迎您!随意将答案标记为已接受,以帮助面临同样问题的人。
    猜你喜欢
    • 2018-02-21
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2014-09-16
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多