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

如何将txt文件中逗号分隔字符串转换为指定结构tuple组成的列表

代码修改方法

核心逻辑是将每一行拆分得到的4个元素做切片拆分,分别打包为元组后组成目标pair结构,修改后的可用代码如下:

import os
path = os.getcwd()
def gettest() -> list:
    # 用os.path.join拼接路径可兼容Windows、Linux、Mac等不同操作系统的路径分隔符
    with open(os.path.join(path, "health-train.txt"), encoding='utf-8') as f:
        line_list = f.read().splitlines()
        # 列表推导式实现结构转换
        res = [ (tuple(parts[:3]), tuple(parts[3:])) for parts in (line.strip().split(',') for line in line_list if line.strip()) ]
    return res

如果你更喜欢可读性更高的写法,也可以用普通循环实现:

import os
path = os.getcwd()
def gettest() -> list:
    res = []
    with open(os.path.join(path, "health-train.txt"), encoding='utf-8') as f:
        for line in f:
            # 跳过空行
            line = line.strip()
            if not line:
                continue
            parts = line.split(',')
            # 拆分后分别打包为元组加入结果
            res.append( (tuple(parts[:3]), (parts[3],)) )
    return res

以上两种写法运行后都可以得到你需要的目标输出结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:06:02