理解理解集

Understanding comprehension sets

好的,我得到了这个代码:

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()

函数上带有正则 for 的结果,returns 这不是我们想要的,因为它只是 returns 第一个对象的对 :

('Transport', 888)

但是有了字典理解,它 returns 那个 json 响应上所有 json 对象的所有插槽对(这很酷)为什么字典理解会抓住所有对而常规 for 不是 ?

Why the dict comprehension grabs all the pairs and the regular for is not ?

当你循环某些东西并在循环中有一个 return 语句时会发生什么,一旦遇到 return 语句,那个值(并且只有那个值)是 returned.

字典理解首先构建整个字典,然后将其作为一个整体 returned 提供给调用者。

这与理解关系不大,与 return 语句关系较大。比较:

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

与:

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