0

Let's say

t1=loadtxt("t\\1.txt")
t2=loadtxt("t\\2.txt")

Assume inside 1.txt is

1 2 3
4 5 6

Assume also inside 2.txt is

1 2 3
4 5 6
#
t1[0,0]=1
t1[0,1]=2
t1[0,2]=3
t2[0,0]=1
t2[0,1]=2
t2[0,2]=3
st=0


for i in range(2):
    for j in range(3):
        a='t'+str(i+1)

        st=st+a

I got "TypeError: string indices must be integers"

What I want this piece of code to do is st=t1[0,0]+t1[0,1]+t1[0,2]+t2[0,0]+t2[0,1]+t2[0,2]

Then how to fulfill this goal? How to represent the array name with regular numbers in for loop? Instead of summing each value one by one.

user3737702
  • 591
  • 1
  • 10
  • 17

2 Answers2

2

Well you could either use a dictionary with all your t's or use the exec built in function. Python 2.x looks like this:

t1 = [1,2,3]
t2 = [1,2,3]
st=0

for i in range(2):
    for j in range(3):
        exec "a = t"+str(i+1)+"["+str(j)+"]"
        st+=a
print st

In Python 3.x you want to use () for the built in functions. Makes the code look like this:

t1 = [1,2,3]
t2 = [1,2,3]
st=0

    for i in range(2):
        for j in range(3):
            exec("a = t"+str(i+1)+"["+str(j)+"]")
            st+=a
    print(st)

The exec function will take a string and act like it was a normal line of code and execute it. This way you can assemble your command and let the interpreter do the rest. (Using String Formatting instead of connecting the string with + might be a better approach though)

Philip Feldmann
  • 7,887
  • 6
  • 41
  • 65
  • But when I run your code, it tells me that " exec "a = t"+str(i+1) ^ SyntaxError: invalid syntax" – user3737702 Dec 11 '15 at 15:24
  • Obviously, because I was giving an example assuming you are using normal variables, not tables like you actually do. I updated my example to fit your a code using tables. – Philip Feldmann Dec 11 '15 at 15:33
  • Somehow the same warning appeared again, " exec "a = t"+str(i+1)+"["+str(j)+"]" ^ SyntaxError: invalid syntax" Is it because the version of python, I am using python 3.4.0 – user3737702 Dec 11 '15 at 15:45
  • Sorry I was assuming you are using pythong 2.x. Python 3.x uses () for all built in functions like print and exec. Just to make it really clear I edited my post for 2.x and 3.x . Hope this helps. – Philip Feldmann Dec 11 '15 at 15:49
  • Wonderful solution!! Although a bit slow, I can have a good sleep tonight~ – user3737702 Dec 11 '15 at 15:51
1

There are ways to do what you want (see link in the comment to your question), but why bother when you can simply do:

st = 0
for t in (t1,t2):
    for i in range(3):
        st += t[0,i]
soungalo
  • 1,106
  • 2
  • 19
  • 34