Skip to content Skip to sidebar Skip to footer

How To Use Map Function On Nested Lists And Converting Strings To Integers?

I would need to use the map function in Python(2.4.4) to add 1 to each item in the list, so I tried converting the strings into integers. line=[['10', '13\n'], ['3', '4\n'], ['5',

Solution 1:

I would use a list comprehension but if you want map

map(lambda line: map(lambda s: int(s) + 1, line), lines)

The list comprehension would be

[[int(x) + 1 for x in line] for line in lines]



>>>lines=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]>>>map(lambda line: map(lambda s: int(s) + 1, line), lines)
[[11, 14], [4, 5], [6, 4], [2, 14]]

>>>[[int(x) + 1for x in line] for  line in lines]
[[11, 14], [4, 5], [6, 4], [2, 14]]

Solution 2:

Well your intent is not clear but it is not due to \n.

See :

>>>line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]>>>map(lambda X:([int(X[0])+1, int(X[1]) +1]),line)
[[11, 14], [4, 5], [6, 4], [2, 14]]

Solution 3:

Converting strings with newlines to an integer is not a problem (but int("1a") would be ambiguous, for example, so Python doesn't allow it).

The mapping in your code passes a sublist to the lambda function, one after another. Therefore you need to iterate over the inner lists again:

>>>line = [['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]>>>printmap(lambda sublist: map(int, sublist), line)
[[10, 13], [3, 4], [5, 3], [1, 13]]

For increasing by one, it would be as simple as above:

map(lambda sublist: map(lambda x: int(x)+1, sublist), line)

Solution 4:

Using argument unpacking.

pairs=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]
[[int(x) + 1, int(y) + 1] for x, y in pairs]

One loop, no lambda.

Post a Comment for "How To Use Map Function On Nested Lists And Converting Strings To Integers?"