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

Python如何将含字符串与整数的元组列表按要求写入txt文件

错误原因

  • 执行for i in sortedlist遍历时,变量i本身就是列表中的元组元素(例如首次循环i的值为('hello', 41)),不属于整数类型的下标索引,因此不能作为参数传入sortedlist[]中取值,这是抛出TypeError的核心原因。
  • 元组取值需要使用方括号[],你代码中使用的圆括号()是调用可执行对象的语法,属于用法错误。
  • 原代码没有添加制表符分隔、换行符,即使运行成功也无法得到符合格式要求的输出。

正确实现代码

推荐使用元组解包的写法,逻辑更清晰:

with open("output/test.txt", "w") as out_file:
    for text, num in sortedlist:
        out_file.write(f"{text}\t{num}\n")

如果习惯用索引取值,也可以使用如下写法:

with open("output/test.txt", "w") as out_file:
    for item in sortedlist:
        out_file.write(item[0] + "\t" + str(item[1]) + "\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:03