我一直在尝试stringify
list
和list of list
,然后将其转换回原始形式。以下是我的2个样本lists
:
option_list = ['1309', '1P09', 'Bdg 1', '1226', 'Bdg 1']
option_listoflist = [['1309', 'Blg 1', 500], ['1P09', 'Bdg 1', 4501], ['1226', 'Bdg 1', 600], ['1302', 'Bdg 1', 1432]]
我根据一些SO帖子编写了这个python
代码,我正在尝试stringify
上面的lists
,然后尝试将它们转换回来,但它会抛出错误:
str1 = ''.join(option_list)
print(str1+'\n')
str_2_list = ast.literal_eval(str1)
print(str_2_list)
str2 = ''.join(option_listoflist)
print(str2+'\n')
str_2_listoflist = ast.literal_eval(str2)
print(str_2_listoflist)
当我执行此操作时,我在invalid syntax
处收到str_2_list = ast.literal_eval(str1)
错误。
我如何stringify
list
和list of list
然后将其转换回原始形式?
注意:我想要做的是将['1309', '1P09', 'Bdg 1', '1226', 'Bdg 1']
转换为此版本"['1309', '1P09', 'Bdg 1', '1226', 'Bdg 1']"
的字符串版本,然后将其转换回原始列表。类似的列表列表
答案 0 :(得分:1)
你做错了 - 转换为字符串。试试str1 = str(options_list)
答案 1 :(得分:1)
由于您似乎正在尝试复制JavaScript JSON.stringify
,因此只需使用json
模块即可:
In [1]: import json
In [2]: option_list = ['1309', '1P09', 'Bdg 1', '1226', 'Bdg 1']
In [3]: option_listoflist = [['1309', 'Blg 1', 500], ['1P09', 'Bdg 1', 4501], ['1226', 'Bdg 1', 600], ['1302', 'Bdg 1', 1432]]
In [4]: json.dumps(option_list)
Out[4]: '["1309", "1P09", "Bdg 1", "1226", "Bdg 1"]'
In [5]: json.dumps(option_listoflist)
Out[5]: '[["1309", "Blg 1", 500], ["1P09", "Bdg 1", 4501], ["1226", "Bdg 1", 600], ["1302", "Bdg 1", 1432]]'
In [6]: json.loads(json.dumps(option_list)) == option_list
Out[6]: True
In [7]: json.loads(json.dumps(option_listoflist)) == option_listoflist
Out[7]: True
答案 2 :(得分:0)
您的''.join(option_list)
输出'13091P09Bdg 11226Bdg 1'
无法转换为列表,因为输出字符串不符合列表语法。
Crrected Code
option_list = ['1309', '1P09', 'Bdg 1', '1226', 'Bdg 1']
option_listoflist = [['1309', 'Blg 1', 500], ['1P09', 'Bdg 1', 4501], ['1226', 'Bdg 1', 600],['1302', 'Bdg 1', 1432]]
str1 = ','.join(option_list)
print(str1+'\n')
str_2_list = str1.split(',')
print(str_2_list)
str2 = ','.join(str(item) for innerlist in option_listoflist for item in innerlist)
print(str2+'\n')
str_2_listoflist=[str2.split(',')[i:i+3] for i in range(0, len(str2.split(',')), 3)]
for i in str_2_listoflist:
i[2]=int(i[2])
print(str_2_listoflist)
输出:
1309,1P09,Bdg 1,1226,Bdg 1
[' 1309',' 1P09',' Bdg 1',' 1226',' Bdg 1' ]
1309,Blg 1,500,1P09,Bdg 1,4501,1226,Bdg 1,600,1302,Bdg 1,1432
[[' 1309',' Blg 1',500],[' 1P09',' Bdg 1',4501], [' 1226',' Bdg 1', 600],[' 1302',' Bdg 1',1432]]