Python:类型错误:列表索引必须是整数,而不是字符串。

10

我打算在Python上进行矩阵加法(尚未完成),但出现了错误。

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 >

2
尝试将 value = [int(i) for i in x.split()] 更改为 value = [int(k) for k in x.split()]?您在for循环和列表推导式中都使用了 i - fredtantini
由于 0 是一个不可变对象,您可以简化为 a = [ [0]*m for j in range(n) ] - chepner
5个回答

7

您在外层的for循环中使用了i,它是一个整数。然后在循环中您有:

value = [int(i) for i in x.split()]

这将使i成为一个字符串(这就是split返回的内容)。也许你认为在[ ]内部有某种作用域范围?实际上并没有。你遇到了名称冲突,请修改其中一个。

1
请注意,Python 3确实为推导式创建了一个新的作用域。 - chepner
@chepner:发现得真好。 - cdarke

1

你在内部循环中使用了相同的变量。

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

1

除了前两个答案,您将会遇到这个声明的问题:

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)

如果你的mn都是3,那么你将创建一个边长为3的矩阵并将其保存在变量c中。 这样你就不必拆分用户输入。用户可以一次输入一个数字。甚至你可以改变以下行:
x = raw_input()

致:

x = raw_input("{0}. row, {1}. column: ".format(i+1, j+1))

试一试吧!


0

如果您声明了一个 int 类型,在使用时将其当作字典类型,也会出现此错误。

>>> a = []
>>> a['foo'] = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

0
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)

好的!我刚刚弄明白了!谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接