我的代码如下:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
Final = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(X)):
for j in range(len(X)):
for x in range(4):
result[i][j] = X[i][j] + X[i][j]
Final[i][j]=result[i][j]+X[i][j]
for r in Final:
print(r)
我想将X矩阵与其自身相加4次,并将答案作为最终求和矩阵返回。任何人都可以帮我吗?
答案 0 :(得分:1)
yourlist = [5,6,7,8]
for i in range(len(yourlist)-1):
print "Source: " + str(yourlist[i])
print "Destination: " + str(yourlist[i+1]) + "\n"
输出:
Source = 5
Destination = 6
Source = 6
Destination = 7
Source = 7
Destination = 8
答案 1 :(得分:1)
一种方法是使用zip()
函数从列表中生成对,然后迭代这些对以打印您的消息:
l = [5, 6, 7, 8]
for source, dest in zip(l, l[1:]):
print('Source = {}'.format(source))
print('Destination = {}'.format(dest))
输出:
Source = 5 Destination = 6 Source = 6 Destination = 7 Source = 7 Destination = 8
这里的关键是zip()
函数,它通过将每个项目与其后续列表组合在一起工作:
>>> l = [1, 2, 3, 4, 5, 6]
>>> l[1:]
[2, 3, 4, 5, 6]
>>> zip(l, l[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
如果列表的长度不均匀,则最后一项将被删除:
>>> l = [1, 2, 3]
>>> zip(l, l[1:])
[(1, 2), (2, 3)]