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

Python将元组列表按指定带and格式拼接后逐行写入文件

现有问题梳理

现有代码存在两类错误:

  • 语法与逻辑错误
    • 函数体、循环体没有正确缩进,直接运行会报语法错误
    • return 语句放在了文件关闭操作之前,函数执行到return就会终止,文件对象永远不会被关闭,会造成资源泄漏
    • 额外返回了最后一个电影的拼接字符串,不符合写入文件函数的常规设计
  • 拼接逻辑错误
    目前直接用, 拼接所有平台,没有处理最后两个平台之间用and连接的需求,不符合输出格式要求
可行解决方案

核心需要针对平台列表的长度分情况处理拼接逻辑,同时改用with上下文管理器自动处理文件的打开关闭,避免资源泄漏问题。
修正后的代码如下:

def write_streaming_info(filename, movies):
    with open(filename, "w", encoding="utf-8") as movie_file:
        for item in movies:
            # 拆分电影名和平台列表
            movie_name = item[0]
            platforms = list(item[1:])
            plat_count = len(platforms)
            # 分情况拼接平台字符串
            if plat_count == 1:
                plat_str = platforms[0]
            elif plat_count == 2:
                plat_str = " and ".join(platforms)
            else:
                # 前n-1个用逗号拼接,最后加and和最后一个平台
                plat_str = ", ".join(platforms[:-1]) + ", and " + platforms[-1]
            # 拼接完整行写入文件
            full_line = f"{movie_name}: {plat_str}"
            movie_file.write(full_line + "\n")

# 测试调用
movies = [("Chocolat", "Hulu", "Netflix", "Amazon"), ("Skyfall", "HBO Max", "Amazon"), ("Soul", "Disney+")]
write_streaming_info("streaming_movies.txt", movies)

执行后写入文件的内容完全符合预期:

Chocolat: Hulu, Netflix, and Amazon
Skyfall: HBO Max and Amazon
Soul: Disney+

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:36:01