我是 Python 新手,请耐心等待。
我有一个 list -
print(listoffiles)
["{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n"]
我只需要此列表中的文件名,
0_HONOR_1524204351030, 0_HONOR_1524204351030,0_HONOR_1524204351030
我首先这样拆分 -
listoffiles=[i.split(":")[0] for i in listoffiles]
print(listoffiles)
["{'0_HONOR_1524204351030'", "{'0_HONOR_1524204351030'", "{'0_HONOR_1524204351030'"]
然后加入它-
listoffiles=(','.join(str(f) for f in listoffiles))
print(listoffiles)
{'0_HONOR_1524204351030',{'0_HONOR_1524204351030',{'0_HONOR_1524204351030'
在这里,我试图剥离它 -
listoffiles=(str(listoffiles).strip("'{'"))
print(listoffiles)
0_HONOR_1524204351030',{'0_HONOR_1524204351030',{'0_HONOR_1524204351030'
这似乎只适用于第一个元素,所以我也尝试了 -
listoffiles=(str(f).strip("'{'") for f in listoffiles)
print(listoffiles)
<generator object <genexpr> at 0x7fda38837460>
由于效果不佳,我尝试使用正则表达式 -
regex = re.compile(r'^[a-zA-Z0-9_]*$')
newlistoffiles=filter(regex.match,listoffiles)
这个似乎有效,但我无法分离输出-
0_HONOR_15242043510300_HONOR_15242043510300_HONOR_1524204351030
我需要帮助来区分这些。 我发布了整个问题,以便我可以获得有关完成此任务的任何其他更好、更聪明的方法的建议。
最佳答案
使用 ast 模块将字符串字典转换为 python 字典,并使用 keys()
获取所需的键。
例如:
import ast
listoffiles = ["{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n", "{'0_HONOR_1524204351030': 'NEW'}\n"]
listoffiles = map(ast.literal_eval, listoffiles)
print([i.keys()[0] for i in listoffiles])
输出:
['0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030', '0_HONOR_1524204351030']
关于python - 列表上正则表达式过滤器后输出中的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137307/