2014-03-18 121 views
1

我假装获得列表中的特定元素,但是当我尝试执行此操作时收到并显示错误:print linesqueryfile[queryindex],linesqueryfile是列表,queryindex是数字我想要的元素,我想进一步将它拆分为令牌并获得令牌列表中的特定元素。访问由变量Python给出的列表中的元素

我是新来的python,所以我不知道如何做到这一点,如何从列表中访问元素的sintaxis。

这是我的代码:

n=len(linesfile) 

for i in range(0,n): 
    tokens = re.split('\s+', linesfile[i]) 
    queryindex = tokens[1] 
    subjectindex = tokens[2] 

    print queryindex 
    print subjectindex 

    print linesqueryfile[queryindex] 
    print linessubjectfile[subjectindex] 

    tokens = split('\s+', linesqueryfile[queryindex]) 
    queryseqstr = tokens[5] 

linesfile样本:

1 12751 92 566 
1 7415 88 566 
1 1643 87 566 
1 16647 83 566 
1 13697 82 566 
1 13737 82 566 
1 13723 82 566 
1 20413 82 566 
1 22113 82 566 
1 20590 80 566 
2 11612 1657 2008 
2 6084 1305 2008 
2 6085 1292 2008 
2 6087 1290 2008 
2 6086 1283 2008 
2 11627 1276 2008 
2 11633 1275 2008 
2 11634 1274 2008 
2 11629 1268 2008 
2 11599 1267 2008 
3 11621 1794 2061 
3 11623 1623 2061 
+0

是什么'linesfile'样子? – MattDMo

+0

在我们确实可以帮忙之前,我们只是缺少一小部分信息。数据看起来像什么,以及linequeryfile和linessubjectfile中有什么。从目前为止,它看起来像基本的切片,但如果您可以添加额外的信息,它会帮助您获得良好的回应。 –

+0

语法看起来没问题,它在做什么,或者没做... –

回答

2

这应该可以解决您的错误。我猜测queryindex和subjectindex是字符串数字。如果没有,请提供您的错误。

print linesqueryfile[int(queryindex)] 
print linessubjectfile[int(subjectindex)] 

或进行:

queryindex = int(tokens[1]) 
subjectindex = int(tokens[2]) 
1

尝试转换queryindexqueryindex为整数:

n=len(linesfile) 

for i in range(0,n): 
    tokens = re.split('\s+', linesfile[i]) 
    queryindex = int(tokens[1]) 
    subjectindex = int(tokens[2]) 

    print queryindex 
    print subjectindex 

    print linesqueryfile[queryindex] 
    print linessubjectfile[subjectindex] 

    tokens = split('\s+', linesqueryfile[queryindex]) 
    queryseqstr = tokens[5]