访问由变量Python给定的列表中的元素

2024-04-20 04:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我假装要获取列表中的一个特定元素,但当我尝试这样做时收到并出错:print linesqueryfile[queryindex]linesqueryfile是一个列表,queryindex是我想要的元素数,我想进一步将其拆分为令牌,并获取令牌列表中的特定元素。你知道吗

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

这是我的密码:

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

Tags: in元素密码列表forlensplitprint
2条回答

尝试将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]

这将修复您的错误。我猜queryindex和subjectindex是字符串。如果没有,请提供您的错误。你知道吗

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

或制造:

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

相关问题 更多 >