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 conv开发者_JAVA技巧erting 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?
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]]
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]]
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)
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.
精彩评论