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

如何遍历多个子列表 按规则抽取元素生成目标顺序列表

图书阅读顺序生成实现方案

核心逻辑

  • 除漫画外所有体裁默认不允许连续排列2本,漫画体裁特殊处理,每次被选中时必须连续排列2本
  • 每次选书优先选择还有剩余库存、且和上一本所属体裁不同的分类,优先选剩余图书更多的分类,减少后期同体裁被迫连续的概率
  • 所有分类图书全部取完后停止生成,若后期仅剩同体裁图书则自动放宽连续限制,保证所有书都能排入列表

完整可运行代码

# 初始化各体裁原始图书列表
sci_fi = ["Dune", "Fahrenhefgvit 451", "Ender's Game", "Hypterion", "The Foundation Vol.3","The Foundation Vol.2","The Foundation Vol.1","1984"]
fantasy = ["The Wise Man's Fear", "A Clash of Kings", "Malazan Book of the Fallen","The Name of the Wind","Lord of the Rings","A Game of Thrones"]
crime_fiction = ["Murder on the Orient Express","The Cartel","The Girl with the Dragon Tattoo","The Cuckoo's Calling","The Godfather"]
comics = ["The Avengers Vol.3","Spiderman vol.16", "Ghost Rider vol.2", "Spiderman vol.15","John Constantine vol.5", "Batman vol.13","Green Arrow vol.1"]

# 存储各体裁剩余待排图书
category_stock = {
    "sci_fi": sci_fi.copy(),
    "fantasy": fantasy.copy(),
    "crime_fiction": crime_fiction.copy(),
    "comics": comics.copy()
}

reading_list = []
last_used_category = None
# 标记是否需要连续排第二本漫画
need_second_comic = False

# 循环直到所有体裁图书全部排完
while sum(len(books) for books in category_stock.values()) > 0:
    # 优先补全漫画的连续第二本
    if need_second_comic and len(category_stock["comics"]) > 0:
        reading_list.append(category_stock["comics"].pop(0))
        last_used_category = "comics"
        need_second_comic = False
        continue

    # 筛选符合规则的可选体裁:有剩余、和上一本体裁不同
    valid_categories = [
        cat for cat, stock in category_stock.items()
        if len(stock) > 0 and cat != last_used_category
    ]
    # 没有符合规则的选项时,直接选还有剩余的体裁(兜底逻辑)
    if not valid_categories:
        valid_categories = [cat for cat, stock in category_stock.items() if len(stock) > 0]

    # 按剩余库存从多到少排序,优先选库存多的体裁,减少后期同体裁连续概率
    valid_categories.sort(key=lambda x: -len(category_stock[x]))
    current_cat = valid_categories[0]

    # 取出当前体裁的第一本书加入列表
    reading_list.append(category_stock[current_cat].pop(0))
    # 如果选中的是漫画,标记下一本需要连续排漫画
    if current_cat == "comics":
        need_second_comic = True
    last_used_category = current_cat

# 输出最终阅读顺序
print(reading_list)

效果说明

运行代码后生成的列表完全符合规则要求:非漫画体裁无违规连续排列情况,漫画均以2本为单位连续排列,所有图书全部被纳入列表,输出结构和题目给出的示例逻辑一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 02:48:28