2016-03-03 66 views
1

确定,所以我得到这个代码:理解理解设置

class ApiCall(object): 

    def __init__(self, url): 
     self.url = url 

    def call(self): 
     call = requests.get(self.url) 
     response = call.content.decode('utf-8') 
     result = json.loads(response) 
     return result 


class IncomeSources(object): 

    def __init__(self, result): 
     self.result = result 

    def all(self): 
      #This is the dict comprehension 
      #return {(slot['accountLabelType'], slot['totalPrice']) for slot in self.result} 

      for slot in self.result: 

       return (slot['accountLabelType'], slot['totalPrice']) 

def main(): 
      url = ('https://datafeed/api/') 
      api_result = ApiCall(url).call() 
      target = IncomeSources(api_result).all() 
      print(target) 


main() 

具有规则的结果用于在函数,返回这个至极是不希望的,因为它仅返回所述一对所述第一对象的:

('Transport', 888) 

但随着字典的理解,它返回该json响应上的所有json对象的所有槽对(这很酷)为什么dict理解抓取所有对,而常规是不是?

回答

1

为什么字典的理解抓住所有的对和常规是不是?

当你循环一些东西并且在循环中有返回语句时会发生什么,只要遇到返回语句,就返回该值(并且只有那个值)。

词典理解首先构造整个字典,然后作为一个整体返回给调用者。

这与理解和更多与返回语句有关。比较:

>>> def foo(): 
...  for i in range(5): 
...   return i 
... 
>>> foo() 
0 

有了:

>>> def foo(): 
...  return list(range(5)) 
... 
>>> foo() 
[0, 1, 2, 3, 4] 
+0

理解,谢谢! – xavier