处理JSON响应时是否需要嵌套循环? [英] Are nested loops required when processing JSON response?

查看:71
本文介绍了处理JSON响应时是否需要嵌套循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表(JSON响应).每个字典都包含带有字符串列表的键/值对.我正在使用嵌套的for循环处理这些字符串,效果很好.

I have a list of dictionaries (JSON response). Each dictionary contains a key-value pairs with a list of strings. I'm processing these strings using a nested for-loop, which works fine.

但是,我想知道是否可以使用product方法将两个for循环折叠为一个循环.显然我不能在范围函数中使用循环变量a,因为尚未定义.

However, I wondered if it is possible to collapse the two for-loops into a single loop using the product method. Obviously I cannot use the loop-variable a in the range function because it's not defined yet.

有没有一种方法可以在不多次遍历数据的情况下做到这一点?

Is there a way to do this without iterating over the data multiple times?

from itertools import product

dicts = [
    {
        'key1': 'value1',
        'key2': ['value2', 'value3']
    },
    {
        'key1': 'value4',
        'key2': ['value5']
    }
]

count = len(dicts)
for a in range(count):
    for b in range(len(dicts[a]["key2"])):
        print "values: ", dicts[a]["key2"][b]

for a, b in product(range(count), range(len(dicts[a]["key2"]))):
    print("values: ", dicts[a]["key2"][b])

推荐答案

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

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)

这篇关于处理JSON响应时是否需要嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆