2016-01-21 77 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