繁体   English   中英

设置函数以接受形式为startIndex:stopIndex的参数

[英]Setting function to accept arguments of the form startIndex:stopIndex

例如:

print(readLines('B:\input.txt', 0, 3)) //0 and 3 are start and end indexes

会成为:

print(readLines('B:\input.txt', 0:3))

任何帮助表示赞赏

您可以通过将参数转换为字符串来使其工作:

print(readLines('B:\input.txt', "0:3"))

然后将其解压缩到函数中:

def readLines(text, index):
    start, stop = index.split(':')

您可以使用itertools.islice:

from itertools import islice
def read_lines(it,start,stop):
  return list(islice(it,start, stop))
print(read_lines([1,2,3,4,5,6],0,3))
[1, 2, 3]

在文件上:

from itertools import islice


def read_lines(f, start, stop):
    with open(f) as f:
        return list(islice(f, start, stop))

如果只想输出字符串,请使用return " ".join(islice(f, start, stop))

如果要处理这些行,只需遍历islice对象:

def read_lines(f, start, stop):
    with open(f) as f:
        for line in islice(f, start, stop):
            do stuff

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM