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

Python中如何按指定交替规则将4个列表的元素合并为单个列表

多列表按动态比例合并实现方案

实现思路

核心逻辑是动态维护活跃的待取数列表,每一轮按预设的数量从各列表取数,自动过滤已耗尽的列表,直到所有列表元素都被取完。

完整代码实现

# 生成测试用的4个数字列表
a = list(range(1, 101))
b = list(range(101, 201))
c = list(range(201, 301))
d = list(range(301, 401))

def merge_by_ratio(*list_config):
    """
    按指定比例合并多个列表
    list_config参数格式:(待合并列表, 单次取数个数)
    """
    result = []
    # 初始化活跃配置,过滤初始为空的列表
    active_config = [ (lst, cnt) for lst, cnt in list_config if lst ]
    while active_config:
        next_round_config = []
        for current_lst, take_count in active_config:
            # 取当前列表前take_count个元素
            taken_elements = current_lst[:take_count]
            result.extend(taken_elements)
            # 剩余元素留待下一轮处理
            remaining_lst = current_lst[take_count:]
            if remaining_lst:
                next_round_config.append( (remaining_lst, take_count) )
        active_config = next_round_config
    return result

# 按需求传入配置,生成结果列表e
e = merge_by_ratio(
    (a, 4),
    (b, 3),
    (c, 2),
    (d, 2)
)

效果验证

打印结果前20个元素即可验证符合要求:

print(e[:20])
# 输出:[1, 2, 3, 4, 101, 102, 103, 201, 202, 301, 302, 5, 6, 7, 8, 104, 105, 106, 203, 204]

特性说明

  • 自动适配列表耗尽的场景:当a列表先被取空后,后续轮次会自动按3:2:2的比例取剩下三个列表的元素,不需要额外写判断逻辑
  • 扩展性强:如果后续需要调整取数比例、增减待合并列表,只需要修改merge_by_ratio的传入参数即可,核心逻辑不用改动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:15:05