Python 如何在嵌套列表上使用映射函数并将字符串转换为整数?
我需要使用Python(2.4.4)中的map函数向列表中的每个项目添加1,因此我尝试将字符串转换为整数Python 如何在嵌套列表上使用映射函数并将字符串转换为整数?,python,Python,我需要使用Python(2.4.4)中的map函数向列表中的每个项目添加1,因此我尝试将字符串转换为整数 line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']] map(lambda X:(X+1),int(line)) 这是否因为\n和巢穴而不起作用?您的意图不清楚,但不是因为\n 见: 我会使用列表理解,但如果您想要map map(lambda line: map(lambda s: int(s) + 1, line)
line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]
map(lambda X:(X+1),int(line))
这是否因为
\n
和巢穴而不起作用?您的意图不清楚,但不是因为\n
见:
我会使用列表理解,但如果您想要
map
map(lambda line: map(lambda s: int(s) + 1, line), lines)
清单将是
[[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]]
将带有换行符的字符串转换为整数并不是问题(例如,
int(“1a”)
将是不明确的,因此Python不允许这样做)
代码中的映射将子列表一个接一个地传递给lambda函数。因此,您需要再次迭代内部列表:
>>> 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]]
如果增加1,则简单如下:
map(lambda sublist: map(lambda x: int(x)+1, sublist), line)
使用参数解包
pairs=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]
[[int(x) + 1, int(y) + 1] for x, y in pairs]
一个循环,没有lambda。好吧,这是我得到的错误:
TypeError:int()参数必须是字符串或数字,而不是“list”
您需要遍历列表中的列表,而不仅仅是第一个列表(其中包含list类型的成员)。该方法很有意义。谢谢,谢谢,但是需要一张地图。
pairs=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']]
[[int(x) + 1, int(y) + 1] for x, y in pairs]