Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何将二维列表内容以特定格式写入文件?_Python 3.x - Fatal编程技术网

Python 3.x 如何将二维列表内容以特定格式写入文件?

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

我有一个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
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 find
code
这就是为什么我说您的
2
可能是一个打字错误。你确定它不是真正的
'2'
,就像其他子列表中的数字一样吗?实际上-我正在将它从'3'修改为'2',以更新数量
code
r[2]=int(r[2])-1
code
。我是否应该在将其写入文件之前将其转换回字符串?是的,您的数字应该是字符串,以便与其余项目的数据类型保持一致。谢谢。。。。当我尝试这个-我得到一个错误
code
r[2]=str(r[2])TypeError:“list”对象在
list
中是不可调用的
code
…Case Beast',2…
,但是在期望输出
Beast\u 3
中,这是一个输入错误吗?