我是Python的新手,我编写了下面的代码,它返回一个Pascal三角形的第k行,其中k作为'rowIndex'参数提供。问题出现在map函数中,其中并置[0]+row
工作正常,但row+[0]
不起作用,并且正在抛出错误,如下所示。在使用zip而不是map(在下面的代码中注释掉)实现的代码中没有出现此问题。任何人都可以指出问题是什么吗?
提前致谢!
错误:
row = [map(lambda a,b:a + b,[0] + row,row + [0])]
TypeError:+:'int'和'list'
的不支持的操作数类型
代码:
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for _ in range(rowIndex):
row = [map(lambda a, b: a + b, [0]+row, row+[0])]
# row = [x + y for x, y in zip([0]+row, row+[0])]
return row
obj = Solution()
print obj.getRow(3)
答案 0 :(得分:4)
map
返回一个列表,不应该用[...]
包装它。
>>> map(lambda a, b: a + b, [0,1,2], [1,2,0]) # Python 2.x
[1, 3, 2]
通过使用[..]
包装它,您将获得一个列表列表;这将在第一次迭代后导致TypeError
:
>>> [map(lambda a, b: a + b, [0,1,2], [1,2,0])]
[[1, 3, 2]]
row = map(lambda a, b: a + b, [0]+row, row+[0])
如果您使用的是Python 3.x,map
将返回一个迭代器;您需要使用list
函数将其转换为列表以获取列表对象:
>>> map(lambda a, b: a + b, [0,1,2], [1,2,0]) # Python 3.x
<map object at 0x7f5acef0a0b8>
>>> list(map(lambda a, b: a + b, [0,1,2], [1,2,0]))
[1, 3, 2]
row = list(map(lambda a, b: a + b, [0]+row, row+[0]))