我有一个像这样的字符串列表
["['List one', 'F, U','P']",
"['List Two', 'J, C, D,I']",
"['List Three', 'W']",
"['List Four', 'Y, B','E, H, M','L, N']"]
我会列出将其转换为像这样的字典列表
{
List One: ['F','U','P'],
List Two: ['J','C','D','I'],
List Three: ['W'],
List Four: ['Y', 'B','E','H','M','L', 'N']
}
我找到了类似的例子,但没有足够接近
答案 0 :(得分:0)
最短路:
import itertools
import re
res = {eval(i)[0]: list(itertools.chain.from_iterable([re.split('\W+', j) for j in eval(i)[1:]])) for i in input_list}
最快的方式:
import itertools
import re
res = {}
for i in input_list:
l = eval(i)
res[l[0]] = list(itertools.chain.from_iterable([re.split('\W+', j) for j in l[1:]]))
为了增强稳健性,请使用ast.literal_eval
代替eval
(由Maarten建议)