You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何迭代生成对应元素映射的指定结构嵌套字典列表?

Fixing the Nested Dictionary List Generation

The issue with your original code is that you’re adding an extra nested loop which creates all possible combinations of text and class values instead of pairing elements by their matching indices. Here’s how to generate the exact nested structure you need, efficiently and scalable for larger datasets:

Correct Solution Using List Comprehensions

This is the most concise and efficient approach for Python:

import numpy as np

class_data = [np.array(['class3','class5']), np.array(['claas1','class9'])]
data = [['dog.txt','cat.txt'], ['mouse.txt','horse.txt']]

# Generate the nested list of dictionaries
out_data = [[{'text': text, 'class': cls} for text, cls in zip(text_group, class_group)] 
            for class_group, text_group in zip(class_data, data)]

print(out_data)

Explicit Loop Version (For Clarity)

If you prefer a more verbose, step-by-step approach:

import numpy as np

class_data = [np.array(['class3','class5']), np.array(['claas1','class9'])]
data = [['dog.txt','cat.txt'], ['mouse.txt','horse.txt']]

out_data = []
# Iterate over each pair of class group and text group
for class_group, text_group in zip(class_data, data):
    sub_list = []
    # Pair each text with its corresponding class at the same index
    for text, cls in zip(text_group, class_group):
        sub_list.append({'text': text, 'class': cls})
    out_data.append(sub_list)

print(out_data)

How It Works

  1. zip(class_data, data) pairs each sublist of classes with its matching sublist of text files.
  2. For each paired group, zip(text_group, class_group) matches each text file with the class at the exact same index—this avoids the unwanted full combinations from your original code.
  3. Both approaches scale seamlessly for larger datasets because they run in linear time relative to the total number of elements, using minimal memory.

Output

Both solutions will produce your desired result:

[[{'text': 'dog.txt', 'class': 'class3'}, {'text': 'cat.txt', 'class': 'class5'}], [{'text': 'mouse.txt', 'class': 'claas1'}, {'text': 'horse.txt', 'class': 'class9'}]]

内容的提问来源于stack exchange,提问作者user14305909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:07:49