Python for循环矩阵

时间:2017-09-18 14:04:14

标签: python numpy

我有一个小python程序的问题,以交叉匹配两个数组。作为旁注,我现在正在学习用Python编写代码,所以我假设我在这里犯了一些令人难以置信的微不足道的错误。 基本上,我想打开两个.txt文件,从每个文件创建一个2D数组,并比较它们,看它们是否有共同的元素。 到目前为止,我做了类似的事情

#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....

但我收到了一般错误

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

我认为问题可能就是那个

mod_nrows = models.shape[0]

没有返回int(应该是函数range()的参数),我试图将两个for循环更改为

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

但我仍然遇到同样的错误。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

任何for循环都应以冒号(:)结尾。

结肠需要主要是为了增强可读性。 Python文档明确提到了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....
相关问题