为什么while循环坚持raw_input?(Python) [英] Why while loop is sticking at raw_input? (python)

查看:22
本文介绍了为什么while循环坚持raw_input?(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图通过将文件读入列表并一次打印 10 行,然后询问用户是否要打印接下来的 10 行(打印更多...).问题是 raw_input 一次又一次地询问输入,如果我给 'y' 或 'Y' 作为输入并且不继续 while 循环,如果我给任何其他输入,while 循环会停止.我的代码可能不是最好的,因为我正在学习 Python.

In the following code i am trying to make a "more" command (unix) using python script by reading the file into a list and printing 10 lines at a time and then asking user do you want to print next 10 lines (Print More..). Problem is that raw_input is asking again and again input if i give 'y' or 'Y' as input and do not continue with the while loop and if i give any other input the while loop brakes. My code may not be best as am learning python.

import sys
import string
lines = open('/Users/abc/testfile.txt').readlines()
chunk = 10
start = 0

while 1:
    block = lines[start:chunk]
    for i in block:
        print i
    if raw_input('Print More..') not in ['y', 'Y']:
        break
    start = start + chunk

我得到的这段代码的输出是:-

Output i am getting for this code is:-

--
10 lines from file

Print More..y
Print More..y
Print More..y
Print More..a

推荐答案

正如@Tim Pietzcker 所指出的,这里不需要更新 chunk,只需使用 start+10> 而不是 chunk.

As @Tim Pietzcker pointed out, there's no need of updating chunk here, just use start+10 instead of chunk.

block = lines[start:start+10]

并使用 start += 10 更新开始.

另一种使用 itertools.islice() 的替代解决方案:

Another alternative solution using itertools.islice():

 with open("data1.txt") as f:
    slc=islice(f,5)            #replace 5 by 10 in your case
    for x in slc:
        print x.strip()
    while raw_input("wanna see more : ") in("y","Y"):     
        slc=islice(f,5)        #replace 5 by 10 in your case
        for x in slc:
            print x.strip()

这个输出:

1
2
3
4
5
wanna see more : y
6
7
8
9
10
wanna see more : n

这篇关于为什么while循环坚持raw_input?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆