将嵌套列表中的所有元素转换为整数

时间:2018-09-17 06:50:23

标签: python python-3.x

我有一个以整数作为字符串的列表,所以如何将其转换回

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]]

有帮助吗?

5 个答案:

答案 0 :(得分:8)

使用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]]

答案 1 :(得分:2)

天真的解决方案:

>>> 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]]

答案 2 :(得分:1)

您可以使用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]]

答案 3 :(得分:1)

final_lst = []


for s in lst:
  sublist = []
  for item in eval(s):
     sublist.append(int(item))
  final_lst.append(sublist)

print(final_lst) 

答案 4 :(得分:1)

您只需eval主列表中的每个列表,然后解析子列表中的每个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]]