我对蟒蛇很陌生,所以请容忍我。
我有一份名单-
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我需要帮助把它们分开。我张贴了整个问题,以便我可以得到任何其他更好和聪明的方式来完成这项任务的建议。
发布于 2018-05-02 14:47:25
使用ast模块将string转换为python,并将keys()转换为所需的键。
Ex:
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']发布于 2018-05-02 14:43:57
您可以使用拆分来分离数据:
#!/usr/bin/env python
Data = ["{'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"]
for i in Data:
i = i.strip()
i = i[2:]
i = i[0:i.index("'")]
print(i)将印刷:
0_HONOR_1524204351030
0_HONOR_1524204351030
0_HONOR_1524204351030
0_HONOR_1524204351030
0_HONOR_1524204351030发布于 2018-05-02 15:03:11
下面是另一种将其分成几个列表的方法:
all_strs = [j for i, j in enumerate(lst)]
#assumes that this string format will remain constant
lsts = [list(all_strs[i])[2:23] for i, j in enumerate(all_strs)]
keys = [''.join(j) for i, j in enumerate(lsts)]
print(keys)
['0_HONOR_1524204351030',
'0_HONOR_1524204351030',
'0_HONOR_1524204351030',
'0_HONOR_1524204351030',
'0_HONOR_1524204351030']https://stackoverflow.com/questions/50137307
复制相似问题