python - 为什么这样一段代码会数组越界?
本文介绍了python - 为什么这样一段代码会数组越界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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]
不会出现越界。
这篇关于python - 为什么这样一段代码会数组越界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文