Convert strings of list to list of integers inside a list

匿名 (未验证) 提交于 2019-12-03 02:41: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:

[[1,2,3],[10,12,5]] 

回答1:

You should use literal_eval to get actual list object from string.

>>> from ast import literal_eval >>> data =  ['[1,2,3]','[10,12,5]'] >>> data = [literal_eval(each) for each in data] >>> data [[1, 2, 3], [10, 12, 5]] 

literal_eval safely evaluates each object.

>>> help(literal_eval) Help on function literal_eval in module ast:  literal_eval(node_or_string)     Safely evaluate an expression node or a string containing a Python     expression.  The string or node provided may only consist of the following     Python literal structures: strings, numbers, tuples, lists, dicts, booleans,     and None. 

You should always try to avoid using eval function. Read more here.



回答2:

You use ast.literal_eval

import ast l =  ['[1,2,3]','[10,12,5]'] l = [ast.literal_eval(i) for i in l] 


回答3:

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 


回答4:

It is often not recommended, but you could use eval for each string:

fun = ['[1,2,3]','[10,12,5]'] listy = [eval(x) for x in fun] 

Outputs:

[[1, 2, 3], [10, 12, 5]] 

This question provides excellent reason as to why using eval can be a bad idea. I am just presenting it here as an option. eval can pose a large security risk, as you are giving user input the full power of the Python interpreter. Additionally, it violates one of the fundamental principles of programming, which states that all of your executable code should directly map to your source code. Evaluating user input with eval leads to executable code that evidently isn't in your source.

Using ast.literal_eval() is preferable, and Padraic Cunningham's answer addresses how to use it effectively.



回答5:

Use regular expressions:

new_list = [[int(j) for j in re.findall(r'\d+', i)] for i in old_list] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!