[英]python convert string representation of nested list of integers to nested list of integers
[英]Convert all element in the nested list to integers
我有一個以整數作為字符串的列表,所以如何將其轉換回
lst = ["['1','2']", "['2','4']", "['1','4']", "['1','5']", "['3','5']", "['3','4']"]
我試圖使用列表理解
[j for j in i if j.isdigit() for i in lst ]
但它返回
['3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4']
所需的輸出:
[[1,2],[2,4],[1,4],[1,5],[3,5],[3,4]]
有什么幫助嗎?
使用ast
模塊。
例如:
import ast
lst = ["['1','2']", "['2','4']", "['1','4']", "['1','5']", "['3','5']", "['3','4']"]
res = [list(map(int, ast.literal_eval(i))) for i in lst]
print(res)
輸出:
[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]
天真的解決方案:
>>> lst = ["['1','2']", "['2','4']", "['1','4']", "['1','5']", "['3','5']", "['3','4']"]
>>> [[int(x.strip("'")) for x in s[1:-1].split(',')] for s in lst]
[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]
您可以使用ast模塊的literal_eval
函數和列表理解
>>>[[int(j) for j in ast.literal_eval(i)] for i in lst]
[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]
final_lst = []
for s in lst:
sublist = []
for item in eval(s):
sublist.append(int(item))
final_lst.append(sublist)
print(final_lst)
您只需eval
主列表中的每個列表,然后解析子lista中的每個int
lst = ["['1','2']", "['2','4']", "['1','4']", "['1','5']", "['3','5']", "['3','4']"]
x = [[int(j) for j in eval(i)] for i in lst]
print (x)
輸出
[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.