简体   繁体   中英

How to convert array of strings to int array in python?

我有一个字符串数组 ["[1,3]","[1,5]"] 如何将其转换为 [[1,2],[1,5]]?

You could use a list comprehension to evaluate the strings.

array = [eval(a) for a in array]

As mentioned elsewhere, this is a very risky if your input is unsanitised as it runs code that you may not have written (more info here ) that may exploit your system or cause random errors so if you can find another way that would be optimal.

You could also use json.loads() for every element in the list.

import json
lst =  ["[1,3]","[1,5]"]
output = []
for i in lst:
    output.append(json.loads(i))
print(output)

Output

[[1, 3], [1, 5]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM