Home > Back-end >  Converting nested lists type
Converting nested lists type

Time:11-14

m1 = [[['64,56'], ['77,9'], ['3,55,44,22,11']]]
m2 = [[[64, 56], [77, 9], [3, 55, 44, 22, 11]]]

How do I go from "m1" to "m2"?

CodePudding user response:

You can use list comprehension with split:

m1 = [[['64,56'], ['77,9'], ['3,55,44,22,11']]]
m2 = [[int(x) for x in lst[0].split(',')] for lst in m1[0]]

print(m2) # [[[64, 56], [77, 9], [3, 55, 44, 22, 11]]]

CodePudding user response:

Try this:

m1 = [[['64,56'], ['77,9'], ['3,55,44,22,11']]]
def to_int(l):
  for x in range(0,len(l)):
    if isinstance(l[x],list):
      to_int(l[x])
    else:
      l[x]=[int(y) for y in l[x].split(",")]
to_int(m1)
print(m1)

This function means it doesn't matter how many nested lists there are, the function turns them all to int values.

  • Related