Python 3.x 如何将二维列表内容以特定格式写入文件?
我有一个2D列表,其内容如下:Python 3.x 如何将二维列表内容以特定格式写入文件?,python-3.x,Python 3.x,我有一个2D列表,其内容如下: [['LIB00001', 'Case Beast', 2], ['LIB00002', 'Dressed gold', '4'], ['LIB00003', 'City terror', '5'], ['LIB00004', 'The Fame', '6'], ['LIB00005', 'Sign Fire', '10']] 我想用以下格式将其写入文本文件: LIB00001_Case Beast_3 LIB00002_Dressed gold_4 LIB00
[['LIB00001', 'Case Beast', 2], ['LIB00002', 'Dressed gold', '4'], ['LIB00003', 'City terror', '5'], ['LIB00004', 'The Fame', '6'], ['LIB00005', 'Sign Fire', '10']]
我想用以下格式将其写入文本文件:
LIB00001_Case Beast_3
LIB00002_Dressed gold_4
LIB00003_City terror_5
LIB00004_The Fame_6
LIB00005_Sign Fire_10
有人能帮帮我吗?假设您的列表名为
l
,并且第一个子列表中的整数2
是一个打字错误,它应该是一个字符串'2'
,就像其他子列表一样(或'3'
,根据您的预期输出),以下代码将预期的输出写入文件名
:
with open('filename', 'w') as f:
f.write('\n'.join(map('_'.join, l)))
或者,如果子列表中的某些数字确实是整数,则可以先将它们转换为字符串:
with open('filename', 'w') as f:
f.write('\n'.join(map('_'.join, [[str(i) for i in s]for s in l])))
获取以下错误
code
f.write('\n'.join(map(''.join,self.availablebook)))类型错误:序列项2:预期str实例,int findcode
这就是为什么我说您的2
可能是一个打字错误。你确定它不是真正的'2'
,就像其他子列表中的数字一样吗?实际上-我正在将它从'3'修改为'2',以更新数量code
r[2]=int(r[2])-1code
。我是否应该在将其写入文件之前将其转换回字符串?是的,您的数字应该是字符串,以便与其余项目的数据类型保持一致。谢谢。。。。当我尝试这个-我得到一个错误code
r[2]=str(r[2])TypeError:“list”对象在list
中是不可调用的code
有…Case Beast',2…
,但是在期望输出Beast\u 3
中,这是一个输入错误吗?