首页 > 解决方案 > 在尝试将列表写入 .txt 文件时,并非所有参数都在字符串格式化期间转换

问题描述

我想将列表写入 .txt 文件,这是我的列表:

[('Visible', 'JJ'),
 ('Landscape', 'NN'),
 ('Landscape', 'NN'),
 ('characteristics', 'NNS'),
 ('derived', 'VBN'),
 ('from', 'IN'),
 ('satellite-tracking', 'JJ'),
 ('data', 'NNS'),
 ('of', 'IN'),
 ('wintering', 'VBG'),
 ('habitats', 'NNS'),
 ('used', 'VBN'),
 ('by', 'IN'),
 ('oriental', 'JJ'),
 ('honey', 'NN'),
 ('buzzards', 'NNS'),
 ('in', 'IN'),
 ('Borneo', 'NNP')]

这是我编写该列表的代码:

with open('result.txt', 'w') as filehandle:
    filehandle.writelines("%s\n" % item for item in list)

但不知何故,它显示了以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-47-8d6e1711d648> in <module>()
      3 
      4 with open('cobahasil1.txt', 'w') as filehandle:
----> 5     filehandle.writelines("%s\n" % kata for kata in merged)

<ipython-input-47-8d6e1711d648> in <genexpr>(.0)
      3 
      4 with open('cobahasil1.txt', 'w') as filehandle:
----> 5     filehandle.writelines("%s\n" % kata for kata in merged)

TypeError: not all arguments converted during string formatting

有人能帮我吗?谢谢

标签: pythonlist

解决方案


迭代中的每个项目都是tuple具有 2 个元素的。

所以你只需要提取所有元素:

tuples_list = [('Visible', 'JJ'),
 ('Landscape', 'NN'),
 ('Landscape', 'NN'),
 ('characteristics', 'NNS'),
 ('derived', 'VBN'),
 ('from', 'IN'),
 ('satellite-tracking', 'JJ'),
 ('data', 'NNS'),
 ('of', 'IN'),
 ('wintering', 'VBG'),
 ('habitats', 'NNS'),
 ('used', 'VBN'),
 ('by', 'IN'),
 ('oriental', 'JJ'),
 ('honey', 'NN'),
 ('buzzards', 'NNS'),
 ('in', 'IN'),
 ('Borneo', 'NNP')]

with open('result.txt', 'w') as filehandle:
    filehandle.writelines("%s %s\n" % item for item in tuples_list)

推荐阅读