2

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', '3\n'], ['1', '13']]

map(lambda X:(X+1),int(line))

Is this not working because of \n and the nests?

2
  • 1
    Well, this is the error I get: TypeError: int() argument must be a string or a number, not 'list' Commented Dec 1, 2010 at 19:36
  • 1
    You need to iterate through the lists within the list, instead of just the first list (which has members of type list). Commented Dec 1, 2010 at 19:38

4 Answers 4

6

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) + 1 for x in line] for  line in lines]
[[11, 14], [4, 5], [6, 4], [2, 14]]
Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

That method makes sense. Thanks.
1

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']]
>>> print map(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)

Comments

1

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.

1 Comment

Thanks but a map was required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.