Convert strings of list to list of integers inside a list

前端 未结 5 1620
长发绾君心
长发绾君心 2021-01-28 20:02

I have a list of strings and those strings are lists. Like this: [\'[1,2,3]\',\'[10,12,5]\'], for example. I want to get a list of lists or even every list there: <

5条回答
  •  终归单人心
    2021-01-28 20:19

    You can use ast.literal_eval, eval should generally be avoided:

    l= ['[1,2,3]','[10,12,5]']
    
    from ast import literal_eval
    
    print([literal_eval(ele) for ele in l])
    [[1, 2, 3], [10, 12, 5]]
    

    Or index, split and map:

    print([list(map(int,ele[1:-1].split(","))) for ele in l])
    [[1, 2, 3], [10, 12, 5]]
    

    If you always have the same format splitting is the most efficient solution:

    In [44]: %%timeit                       
    l= ['[1,2,3]','[10,12,5]']
    l = [choice(l) for _ in range(1000)]
    [eval(ele) for ele in l]
       ....: 
    100 loops, best of 3: 8.15 ms per loop
    
    In [45]: %%timeit
    l= ['[1,2,3]','[10,12,5]']
    l = [choice(l) for _ in range(1000)]
    [literal_eval(ele) for ele in l]
       ....: 
    100 loops, best of 3: 11.4 ms per loop
    
    In [46]: %%timeit                       
    l= ['[1,2,3]','[10,12,5]']
    l = [choice(l) for _ in range(1000)]
    [list(map(int,ele[1:-1].split(","))) for ele in l]
       ....: 
    100 loops, best of 3: 2.07 ms per loop
    

提交回复
热议问题