Carlo
Carlo

Reputation: 1586

Python for loop over matrix

I have a problem with a small python program to cross-match two arrays. As a side note, I'm learning to code in Python in these days, so I assume I'm making some incredibly trivial mistake here. Basically, I want to open two .txt files, create a 2D array from each of them, and compare them to see if they have common elements. So far, I did something like this

#creating arrays from files
models  = np.genfromtxt('models.txt', dtype='float')
data    = np.genfromtxt('data.txt', dtype='float')

#obtaining the number of rows in each array
mod_nrows = models.shape[0]
data_nrows = data.shape[0]

#checking line by line if there are ay matches
for i in range(mod_nrows)
    for j in range(data_nrows)
        do stuff....

but I'm getting the generic error

File "crossmatch.py", line 27
   for i in range(mod_nrows)
                        ^
SyntaxError: invalid syntax

I thought the problem might be that

mod_nrows = models.shape[0]

doesn't return an int (which should be the argument of the function range()), and I tried to change the two for loops to

for i in range(int(mod_nrows))
    for j in range(int(data_nrows))
        do stuff....

but I'm still getting the same error. Any suggestions?

Upvotes: 0

Views: 3619

Answers (1)

Amarpreet Singh
Amarpreet Singh

Reputation: 2270

Any for loop should end with a colon (:).

The colon is required primarily to enhance readability. Python docs explicitly mention here

#creating arrays from files
models  = np.genfromtxt('models.txt', dtype='float')
data    = np.genfromtxt('data.txt', dtype='float')

#obtaining the number of rows in each array
mod_nrows = models.shape[0]
data_nrows = data.shape[0]

#checking line by line if there are ay matches
for i in range(mod_nrows):
    for j in range(data_nrows):
        do stuff....

Upvotes: 2

Related Questions