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

如何将制表符分隔的TXT数据转换为指定结构的Python字典

你的现有代码存在几个需要调整的问题:

  1. 直接写chr, start, end = line.split()时,如果行的字段数超过3,会抛出「值太多无法解包」的错误,这也是你没法忽略后续列的核心原因
  2. 你把star_end_list定义在了循环外部,会导致所有字典值共享同一个列表实例,最终所有值都会被覆盖为最后一行的起止数值
  3. append()的语法错误,不需要加赋值符号,正确用法是star_end_list.append(start)

实现代码

你可以用Python的可变长度解包语法直接丢弃后续多余列,同时记得把第二、第三列转成整数类型即可:

result = {}

with open("file.txt", encoding="utf-8") as f:
    for line in f:
        # 先去掉首尾的换行、空白符
        stripped_line = line.strip()
        if stripped_line.startswith("chr"):
            # 这里的*_会接收后续所有多余的字段,直接丢弃不用即可
            chr_name, start, end, *_ = stripped_line.split()
            result[chr_name] = [int(start), int(end)]

如果用的是较低版本的Python不支持上述解包语法,也可以用切片取前3个字段:

result = {}

with open("file.txt", encoding="utf-8") as f:
    for line in f:
        stripped_line = line.strip()
        if stripped_line.startswith("chr"):
            parts = stripped_line.split()
            chr_name = parts[0]
            start = int(parts[1])
            end = int(parts[2])
            result[chr_name] = [start, end]

提示:不建议用chr作为变量名,它是Python内置的整数转字符函数,直接用做变量名会覆盖原有功能,换成chr_name这类命名更安全。

运行后得到的result就是你要求的格式,直接打印即可看到预期输出。

内容的提问来源于stack exchange,提问作者Manolo Dominguez Becerra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:39:02