首页 > 为什么这样一段代码会数组越界?

为什么这样一段代码会数组越界?

import sys
line = sys.stdin.readlines(2)
print ('line' , line)
print (line[0])
print(line[1])

编译器为python3.4.2
当第一个输入的值为 a ,可以正常结束程序,但如果第一个输入的值为 aa ,编译器就报 IndexError: list index out of range


看下面readlines文档:

>>> import sys
>>> print(sys.stdin.readlines.__doc__)
Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.

line = sys.stdin.readlines(2)是要一行一行读入,直到总字节数超过2字节,返回一个数组(注意,不是字符串)。

当输入aa的时候,读入aa\n,超过了两个字节,于是返回['aa\n'],访问line[1]自然越界。

当输入a的时候,读入a\n,不超过两个字节,阻塞在那里,继续输入a,又读入一行a\n,此时读入了4个字节,超过了2个字节,于是返回['a\n', 'a\n'],访问line[1]不会出现越界。

【热门文章】
【热门文章】