Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: TypeError: list indices must be integers, not str

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 <-- matrix dimensional m*n

1 2 3 >

3 2 1 > matrix A

1 3 2 >

1 1 1 >

1 1 1 > matrix B

1 1 1 >

and shows as

2 3 4 >

4 3 2 > matrix A + B

2 4 3 >

like image 845
jojoclt Avatar asked Sep 22 '14 11:09

jojoclt


1 Answers

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()]

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.

like image 83
cdarke Avatar answered Sep 24 '22 09:09

cdarke