Are nested loops required when processing JSON response?

試著忘記壹切 提交于 2019-12-24 01:54:23

问题


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.

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

回答1:


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)

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)



回答2:


Depends on what your goal is. You could do:

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

all_vals = []
for d in dicts:
    all_vals += d['key2']
print(", ".join(all_vals))


来源:https://stackoverflow.com/questions/46529929/are-nested-loops-required-when-processing-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!