Mo Money
Mo Money

Reputation: 9

Converting nested lists type

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"?

Upvotes: 0

Views: 74

Answers (2)

Agent Biscutt
Agent Biscutt

Reputation: 737

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.

Upvotes: 0

j1-lee
j1-lee

Reputation: 13929

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

Upvotes: 1

Related Questions