Python:TypeError:列表索引必须是整数,而不是str [英] Python: TypeError: list indices must be integers, not str
问题描述
我将在Python上做矩阵加法.(未完成).但是它显示了一个错误.
I'm going to do Matrix Addition on Python.(Not finish). But it shows an error.
m, n = (int(i) for i in raw_input().split())
a = [[0 for i in range(m)] for j in range(n)]
b = [[0 for i in range(m)] for j in range(n)]
c = []
total = []
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
我要输入
I want to input
3 3<-矩阵维m * n
3 3 <-- matrix dimensional m*n
1 2 3>
3 2 1>矩阵A
3 2 1 > matrix A
1 3 2>
1 1 1>
1 1 1>矩阵B
1 1 1 > matrix B
1 1 1>
并显示为
2 3 4>
4 3 2>矩阵A + B
4 3 2 > matrix A + B
2 4 3>
推荐答案
您正在for
外部循环中使用i
,它是一个整数.然后在循环中,您可以:
You are using i
in your outer for
loop, and it is an int. Then in the loop you have:
value = [int(i) for i in x.split()]
使得i
成为字符串(split
返回的字符串).也许您认为[ ]
内部存在某种范围界定?没有.您遇到名称冲突,请更改其中之一.
which makes i
a string (which is what split
returns). Maybe you think there is some sort of scoping inside [ ]
? There isn't. You have a name collision, change one of them.
这篇关于Python:TypeError:列表索引必须是整数,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!