Anjith
Anjith

Reputation: 2308

Convert all element in the nested list to integers

I have a list with integers as strings so how can I convert it back

lst = ["['1','2']", "['2','4']", "['1','4']", "['1','5']", "['3','5']", "['3','4']"]

I tried to use a list comprehension

[j for j in i if j.isdigit() for i in lst ]

but it returns

['3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4']

Desired output:

[[1,2],[2,4],[1,4],[1,5],[3,5],[3,4]]

Any help?

Upvotes: 1

Views: 1235

Answers (5)

Ahmed Yousif
Ahmed Yousif

Reputation: 2348

you simply eval every list in the main list then parse every int inside sub lista

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)

output

[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]

Upvotes: 1

Fuji Komalan
Fuji Komalan

Reputation: 2047

final_lst = []


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

print(final_lst) 

Upvotes: 1

Raunaq Jain
Raunaq Jain

Reputation: 917

You can use ast module's literal_eval function and list comprehension

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

Upvotes: 1

mshsayem
mshsayem

Reputation: 18008

Naive solution:

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

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Use ast module.

Ex:

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)

Output:

[[1, 2], [2, 4], [1, 4], [1, 5], [3, 5], [3, 4]]

Upvotes: 8

Related Questions