[英]Why can't I access list element
I am trying to access list element from the token variable, but I keep on getting the error 我正在尝试从令牌变量访问列表元素,但我不断收到错误消息
print token[0]
IndexError: list index out of range'
When I try to access the element from token list. 当我尝试从令牌列表访问元素时。
The contents of the file rebase file are: 文件变基文件的内容为:
ZraI 3 GAC'GTC 0 ! AatII >INV
;ZrmI 3 AGT'ACT 0 ! ScaI,AssI,BmcAI >I
and the code is: 代码是:
with open (rebase_file, 'r') as rebase:
lines = rebase.readlines()
string = ''
for line in lines:
token = line.split()
print token[0]
You encountered an empty line: 您遇到了空行:
>>> ''.split()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Simply test for this with if line.strip():
: 只需使用
if line.strip():
:
with open (rebase_file, 'r') as rebase:
for line in rebase:
if line.strip():
token = line.split()
print token[0]
Note that I loop over the file directly instead of reading it all into memory in one go as well. 请注意,我直接循环遍历该文件,而不是一次全部将其读入内存。
您可能有一个空行,请检查一下。
Looks like line fits this description from the python docs : 看起来这行符合python docs中的以下描述:
splitting an empty string or a string consisting of just whitespace with a None separator returns [] 用空分隔符分割空字符串或仅由空格组成的字符串将返回[]
which means that token is an empty array and token[0] is out of range. 这意味着令牌是一个空数组,令牌[0]超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.