如何将 Python <class 'str'> 转换为 <class 'list'>



我有一个文件,其中有一行很长。行包含嵌套列表,其中每个元素都包含一些整数和字符串,如代码示例所示:

sl = [
[127390,175493,530,1073310,2376580,"Mi:DR 96AII,Yt:DR 94A,AFA:DR 96b","26:17 tooth holes 
(horizontal / vertical)rnwar printrnnew numbering, coarse impression, online YT catalog 
2020","Unveiling of the monument of Emperor William I, Berlin"], 
[127397,57201,530,2607693,2376580,"Mi:DR 103a,Sn:DE 101,Yt:DR 102,Sg:DR 103","","Germania,inscr. 
DEUTSCHES REICH"]
]
print(sl,type(sl)) # type is list
with open('l1.txt', 'r') as f:
l1_list = f.read() # the txt file contains the same as the variable sl 
print(l1_list, type(l1_list)) # type is string

如何将文件内容解释为列表或如何将内容从字符串转换为列表(逗号分隔(

您提供的字符串似乎是Python列表的语法有效字符串表示。如果你的所有数据都是这样,那么这将是你想要的:

import ast
...
with open('l1.txt', 'r') as f:
l1text = f.read()
mylist = ast.literal_eval(l1text) 

我这样测试它:

>>> sl = r"""[[127390,175493,530,1073310,2376580,"Mi:DR 96AII,Yt:DR 94A,AFA:DR 96b","26:17 tooth holes (horizontal / vertical)rnwar printrnnew numbering, coarse impression, online YT catalog 2020","Unveiling of the monument of Emperor William I, Berlin"], [127397,57201,530,2607693,2376580,"Mi:DR 103a,Sn:DE 101,Yt:DR 102,Sg:DR 103","","Germania,inscr. DEUTSCHES REICH"]]"""
>>> x = ast.literal_eval(sl)
>>> x
[[127390, 175493, 530, 1073310, 2376580, 'Mi:DR 96AII,Yt:DR 94A,AFA:DR 96b', '26:17 tooth holes (horizontal \/ vertical)rnwar printrnnew numbering, coarse impression, online YT catalog 2020', 'Unveiling of the monument of Emperor William I, Berlin'], [127397, 57201, 530, 2607693, 2376580, 'Mi:DR 103a,Sn:DE 101,Yt:DR 102,Sg:DR 103', '', 'Germania,inscr. DEUTSCHES REICH']]

我想你想把2D列表变成1D列表。这里是我的建议:

s1 = sum(s1, [])

相关内容

最新更新