python - 访问列表内的元素,由变量 Python 给出

标签 python list token

我假装获取列表中的特定元素,但当我尝试执行此操作时,我收到错误消息: printlinesqueryfile[queryindex], linesqueryfile is a list 和 queryindex 是我想要的元素数量,我想进一步将其拆分为 token 并获取 token 列表中的特定元素。

我是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

最佳答案

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

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

或制作:

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

关于python - 访问列表内的元素,由变量 Python 给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491622/

相关文章:

python - 如果满足条件,则将连续的字符串对连接到列表中

kubernetes - 尽管服务帐户具有权限 "Error from server (Forbidden): ...",但无法获取 Pod

c - 在c中操作字符串

python - 为列表分配内存

java - Spring Boot - 在 ArrayList 中搜索单词并在 GET 中返回

c++ - 为什么我的字符串在 Windows 和 Linux 上通过 strtok 解析不同?

python - 将 XML 字符作为字符串读入 ElementTree

python - 创建一个以数组字符串作为名称的目录

python - AttributeError : 'NoneType' object has no attribute 'group' while using re. 匹配文件名重命名

python - 在 python 的 max 函数中传递 1 2 23 32 4 返回 4,为什么?