我希望你能帮助我熟练掌握列表的使用,我已经了解到列表推导式并且阅读了大量相关资料,但是有一个问题一直困扰着我。
考虑以下挑战:
def matrix_mult(m1, m2):
"""
>>> matrix_mult([[1, 2], [3, 4]], [[5, 6], [7, 8]])
[[19, 22], [43, 50]]
>>> matrix_mult([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 1], [2, 3]])
[[31, 19], [85, 55]]
>>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]])
[[39, 54, 69], [13, 23, 33], [14, 19, 24]]
"""
我创建了这个解决方案,对我来说它似乎是最合乎逻辑的,并且符合我的以往编程经验,我差不多是边思考边打字...
# 1 using a traditional List buildup method
res = []
for i in range(len(m1)):
sub = []
for j in range(len(m2[0])):
sub.append(row_times_column( m1, i, m2, j ))
res.append(sub)
return res
然后我找到了这个解决方案,它使用了“列表推导式”(我将变量重命名以匹配我的变量,以便更好地理解两个解决方案之间的差异:
# 2 using list comprehension
res = [[0] * len(m1) for x in xrange(len(m2[0]))]
for i in range(len(res)):
for j in range(len(res[i])):
res[i][j] = row_times_column(m1, i, m2, j)
return res
第二种解决方案是构建一个与预期答案形状相匹配的零基矩阵,但这种方法是否就是所谓的“列表推导”?还是这里有更多的东西?以下是row_times_column()函数的完整定义。
def row_times_column(m1, row, m2, column):
"""
>>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0)
19
>>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1)
22
"""
i = 0
for index, value in enumerate(m1[row]):
i += value * m2[index][column]
return i
我怀疑有第三种(甚至更多)使用lambda解决这个问题的方法,但我想先请教一下这两种方法的评论。
示例摘自http://openbookproject.net/thinkcs/python/english2e/ch09.html
编辑 现在对列表推导式有了更好的掌握,感谢这里给出的答案。
仍然有人能够解释创建一个空矩阵并将正确答案放入其中的逻辑,而不是创建一个新列表吗?
res[i][j] =
语法会报错,因为项不存在;所以你必须使用res.append()
,虽然这种语法不如这里优雅。我认为这是唯一的原因。 - littlegreen