gpt4 book ai didi

python - 如何摆脱数组中的内置引号并保存到文件中

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:28 25 4
gpt4 key购买 nike

我有一个像这样的二维数组:

  [["x","0xacc2d9"],
["y","0x56ae57"]]

我想保存这个数组,使其保留二维数组。第一项有报价,第二项没有报价。

所以保存在文件中的结果应该是:

 [["x",0xacc2d9],
["y",0x56ae57]]

我尝试了各种方法,但由于引文不是额外的东西而且是内置的,所以我无法删除它。我试过了。

lst. replace(""",")

另外,这个:

filename= 'test.txt'
with open(filename, 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerows(lst)

但它删除了 [] 、 "",我不想删除它们。

感谢您的帮助。

编辑2出于某种原因,我需要我的输出有双引号不是单引号所以输出必须是:which x has double quotation

   [["x",0xacc2d9],
["y",0x56ae57]]

最佳答案

不完美,但它给了你一些可以玩的东西:

In [883]: lst =  [["x","0xacc2d9"], 
...: ["y","0x56ae57"]]
In [885]: with open('test.txt','w') as f:
...: f.write('[')
...: for row in lst:
...: f.write('[%r, %s]\n'%tuple(row))
...: f.write(']\n')
...:
In [886]: cat test.txt
[['x', 0xacc2d9]
['y', 0x56ae57]
]

你打算如何使用这个文件?

为了更简洁地处理外括号(和引号替换):

In [887]: astr = '\n'.join(['[%r, %s]'%tuple(row) for row in lst])              
In [888]: astr
Out[888]: "['x', 0xacc2d9]\n['y', 0x56ae57]"
In [895]: astr = astr.replace("'",'"')
In [896]: astr
Out[896]: '["x", 0xacc2d9]\n["y", 0x56ae57]'
In [897]: with open('test.txt','w') as f:
...: print('[%s]'%astr, file=f)
...:
In [898]: cat test.txt
[["x", 0xacc2d9]
["y", 0x56ae57]]

关于python - 如何摆脱数组中的内置引号并保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55446141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com