![](/img/trans.png)
[英]'TypeError: list indices must be integers, not str' Python 3
[英]Python: TypeError: list indices must be integers, not str
我要在Python上做Matrix Addition。(没有完成)。 但它显示错误。
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
我想输入
3 3 < - 矩阵维m * n
1 2 3>
3 2 1>矩阵A.
1 3 2>
1 1 1>
1 1 1>矩阵B.
1 1 1>
并显示为
2 3 4>
4 3 2>矩阵A + B.
2 4 3>
你在你的外部for
循环中使用i
,它是一个int。 然后在循环中你有:
value = [int(i) for i in x.split()]
这使i
成为一个字符串(这是split
返回)。 也许你认为[ ]
里面有某种范围? 没有。 你有一个名字冲突,改变其中一个。
你在内部for循环中使用相同的变量。
for i in range(m):
x = raw_input()
for j in range(n):
# variable i is refering to outer loop
value = [int(p) for p in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
除了前两个答案之外,您将对此声明产生问题:
c[i][j] = a[i][j]
当循环开始时i
将为0并且到目前为止确定,但是c
是空列表并且在第一个位置没有可迭代,因此c[0][0]
将返回错误。 摆脱它并取消注释以下行:
#c.append(value)
编辑:
您的代码不会返回您想要的内容。 你最好做这样的事情来创建一个给定边的矩阵:
for i in range(m):
d = []
for j in range(n):
x = raw_input()
d.append(int(x))
c.append(d)
如果m
和n
都有3,那么你将创建保存在变量c
中的边3 x 3的矩阵。 这样您就不必拆分用户输入。 用户可以一次给出一个号码。 你甚至可以改变以下行:
x = raw_input()
至:
x = raw_input("{0}. row, {1}. column: ".format(i+1, j+1))
试试看!
import time
m, n = (int(i) for i in raw_input().split())
a = []
b = []
total = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
a.append(value)
#print a
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
b.append(value)
#print b
for i in range(m):
for j in range(n):
total[i][j] = a[i][j] + b[i][j]
for i in total:
print ' '.join(map(str, i))
time.sleep(2)
好! 我只想出来了! 谢谢
如果你声明一个int并将其视为dict,你也可以点击这个错误
>>> a = []
>>> a['foo'] = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.