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

Python实现两个列表合并生成指定格式的TXT表格

列表合并解决方案

需求说明

将以下两个列表合并为指定格式的newlist:13个影厅(ordersalles)对应25部影片(orderfilms),前12个影厅各对应2部影片,最后1个影厅仅对应1部影片。最终每个元素格式为影厅名\t影片1, 影片2\n(最后一个元素为影厅名\t影片\n)。

待合并列表:

ordersalles = ['Salle 13', 'Salle 06', 'Salle 12', 'Salle 10', 'Salle 11', 'Salle 08', 'Salle 07', 'Salle 01', 'Salle 04', 'Salle 09', 'Salle 03', 'Salle 05', 'Salle 02']
orderfilms = ['Bullet train', 'Carter', 'Sita Ramam', 'L’année du requin', 'Les Promesses d’Hasan', 'Luck', 'Ménestrel', 'Wedding Season', 'Poikkal Kudhirai', 'Des feux dans la nuit', 'The Bikeriders', 'Darling', 'Treize vies', 'En décalage', 'Night Raiders', 'The Last Son', 'Embuscade', 'Mission Eagle', 'Le Destin des Tortues Ninja, le Film', 'Amants Super-héroïques', 'Doblemente Embarazada', 'Alina of Cuba', 'Prey', 'La Vie en plus grand', 'Hero Mode']

正确实现代码

newlist = []
film_pos = 0
total_salles = len(ordersalles)

for idx, salle in enumerate(ordersalles):
    # 判断当前影厅是否为最后一个
    if idx < total_salles - 1:
        # 前12个厅各取2部影片
        selected_films = orderfilms[film_pos:film_pos+2]
        film_pos += 2
    else:
        # 最后一个厅取剩余的1部影片
        selected_films = orderfilms[film_pos:]
    
    # 拼接成指定格式的字符串
    film_str = ', '.join(selected_films)
    newlist.append(f"{salle}\t{film_str}\n")

错误代码分析

你之前尝试的嵌套循环逻辑完全不符合需求:

# 错误代码
newlist = []
for i in ordresalles:
    for e in ordre films:
        newlist.append(i)
        newlist.append(e)

这段代码会把每个影厅和所有影片逐一配对,最终生成的列表长度为13*25=325,完全偏离了“每个影厅对应1-2部影片”的目标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:10:30