python - 为什么这样一段代码会数组越界?
巴扎黑
巴扎黑 2017-04-17 17:21:35
[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

巴扎黑
巴扎黑

全部回复(1)
迷茫

看下面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]不会出现越界。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号