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

Python 2.7中3D列表的发送者接收者组合生成与扁平化处理

Python 2.7 数据分类拆分与组合生成方案

需求说明

处理给定的3D列表,每个主列表元素包含两个子列表(分别作为发送者SENDER和接收者RECEIVER),生成两者的所有两两组合,保留原结构中的非列表元素位置,最终将结果扁平化。

实现代码

data = [
    [['FTIM@whitelist.es'],['TTT@hi.com','JORDI@jordilazo.com'],'a','b'],
    ['a',['PEP@hi.com','LAZO@jordilazo.com','ZORO@hi.com'],['GOKU@jordilazo.es'],'b'],
    [['t3'],['y1','y2','y3','y4'],'a','b'],
    ['b',['r1@m.com','r2@m.com'],'a',['t4@m.com','t5@m.com']]
]

def process_single_entry(entry):
    # 分离当前条目里的两个子列表(发送者、接收者)和其他非列表元素
    sublists = [elem for elem in entry if isinstance(elem, list)]
    # 生成所有发送者与接收者的组合,并重构条目结构
    sender_list, receiver_list = sublists[0], sublists[1]
    combined_entries = []
    
    for sender in sender_list:
        for receiver in receiver_list:
            new_entry = []
            for elem in entry:
                if elem is sender_list:
                    new_entry.append(sender)
                elif elem is receiver_list:
                    new_entry.append(receiver)
                else:
                    new_entry.append(elem)
            combined_entries.append(new_entry)
    
    return combined_entries

# 处理所有主列表元素
all_combined = []
for entry in data:
    all_combined.extend(process_single_entry(entry))

# 扁平化最终结果
flattened_result = [item for sublist in all_combined for item in sublist]

# 输出结果
print(flattened_result)

代码说明

  1. 元素分离:通过类型判断,从每个主列表元素中拆分出两个子列表(发送者候选、接收者候选),保留其余非列表元素的位置信息。
  2. 组合生成:双重循环遍历发送者和接收者的所有候选元素,生成所有两两组合。
  3. 结构重构:遍历原主列表元素的结构,将对应位置的子列表替换为单个组合元素,确保非列表元素的位置与原结构一致。
  4. 扁平化处理:通过列表推导式将嵌套的组合列表展开为一维列表,满足最终格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:39:19