TypeError:'int'对象没有属性'__getitem __'

时间:2016-10-18 18:36:20

标签: python python-2.7

我尝试创建LCS问题并在编译时遇到错误

Traceback (most recent call last):
  File "lcs.py", line 30, in <module>
    if x[int(i)] == y[int(j)]:
TypeError: 'int' object has no attribute '__getitem__'

以下是我的代码:

from array import array
from pprint import pprint

def maxi(p, q):
 if (p > q):
      return p
 else: 
      return q

x="cgataattgaga"
y="lohttat"
n=len(x)
m=len(y)
l=[[0 for x in range(m+1)] for y in range(n+1)]
#Initializing the first row to be zero
for i in range(0,n+1):
    l[i][0]=0
#Initializing the first column to be zero
for i in range(0,m+1):
    l[0][i]=0
pprint(l)
for i in range(n):
    for j in range(m):

        if x[int(i)] == y[int(j)]:
            l[i+1][j+1]=l[i][j]+1
        else:
            l[i+1][j+1]=maxi(l[i][j+1],l[i+1][j])

#import pprint to print the 2D array in a grid format
pprint(l)

3 个答案:

答案 0 :(得分:1)

您在此处重新分配xy

l=[[0 for x in range(m+1)] for y in range(n+1)]

(循环变量转义)

答案 1 :(得分:1)

问题在于python变量&#34;泄漏&#34;外部理解范围,如果你这样做

x = "tom"
l = [0 for x in range(10)] 
print x

会为您9而不是tom。只需更改理解中变量的名称。

答案 2 :(得分:0)

在这一行

l=[[0 for x in range(m+1)] for y in range(n+1)]

x已被覆盖为整数。 (它不再是一个字符串了)