Python中简化嵌套循环的方法:提取嵌套JSON结构中的目标列表
Absolutely—those deep nested loops are not only hard to read but also a pain to maintain. Let’s look at two cleaner approaches to extract all your example* lists without all the nesting:
Approach 1: Recursive Traversal (Flexible for Any Nested Structure)
If your JSON structure might evolve (e.g., adding more TestX sections or deeper levels), a recursive function is perfect. It will automatically traverse every part of the JSON and collect values where keys start with "example":
import json def extract_example_lists(data): example_lists = [] if isinstance(data, dict): for key, value in data.items(): # Check if this key is an "example" field if key.startswith("example"): example_lists.append(value) else: # Recurse into nested dictionaries/lists example_lists.extend(extract_example_lists(value)) elif isinstance(data, list): # Recurse into each item in the list for item in data: example_lists.extend(extract_example_lists(item)) return example_lists # Usage FILE = "your_config.json" with open(FILE) as config_file: data = json.load(config_file) all_examples = extract_example_lists(data) for example in all_examples: print(example)
This works regardless of how many nested levels you have, and it’s easy to modify if you need to adjust the key matching logic (e.g., exact key names instead of prefixes).
Approach 2: Concise List Comprehension (For Fixed Structure)
If your JSON structure is always going to follow the exact pattern you shared, you can flatten all those nested loops into a single list comprehension. This is more concise and avoids the overhead of recursion:
import json FILE = "your_config.json" with open(FILE) as config_file: data = json.load(config_file) # Flatten the nested structure into a list of example lists all_examples = [ example_value for secure_config in data["SecureConfig"] for test_group in secure_config["Test"] for test_subgroup in test_group.values() for item in test_subgroup for example_value in item.values() ] for example in all_examples: print(example)
Let’s break down what this does:
- Iterate through each entry in
SecureConfig - Then each test group in the
Testlist - Then each subgroup (like
Test1,Test2) usingtest_group.values() - Then each item in those subgroups (the dictionaries with
example*keys) - Finally, extract the value (your list of commands) from each of those dictionaries
Bonus: Better File Handling
Note that I used a with statement to open the file—this ensures the file is automatically closed after reading, which is safer than the open() call in your original code (which leaves the file open unless you explicitly call config_file.close()).
内容的提问来源于stack exchange,提问作者manav sharma

