2014-03-18 90 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]