将无限长度的字符串列表转换为字典python

时间:2017-06-21 05:31:22

标签: python python-3.x data-structures

我有一个像这样的字符串列表

["['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']
}

我找到了类似的例子,但没有足够接近

1 个答案:

答案 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建议)