且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处理JSON响应时是否需要嵌套循环?

更新时间:2023-01-02 17:18:34

虽然您可以将其折叠成一个循环,但这是不值得的:

While you could collapse this into one loop, it's not worth it:

from itertools import chain
from operator import itemgetter

for val in chain.from_iterable(map(itemgetter('key2'), dicts)):
    print("value:", val)

保留嵌套循环并放下笨拙的range-len更具可读性:

It's more readable to just keep the nested loops and drop the awkward range-len:

for d in dicts:
    for val in d['key2']:
        print("value:", val)