[英]Setting function to accept arguments of the form startIndex:stopIndex
For example: 例如:
print(readLines('B:\input.txt', 0, 3)) //0 and 3 are start and end indexes
Would become: 会成为:
print(readLines('B:\input.txt', 0:3))
Any help appreciated 任何帮助表示赞赏
You can make it work by turning the argument into a string: 您可以通过将参数转换为字符串来使其工作:
print(readLines('B:\input.txt', "0:3"))
and then unpacking it in the function: 然后将其解压缩到函数中:
def readLines(text, index):
start, stop = index.split(':')
You can use itertools.islice: 您可以使用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]
On a file: 在文件上:
from itertools import islice
def read_lines(f, start, stop):
with open(f) as f:
return list(islice(f, start, stop))
If you want just the string output use return " ".join(islice(f, start, stop))
如果只想输出字符串,请使用
return " ".join(islice(f, start, stop))
If you want to work on the lines just iterate over the islice object: 如果要处理这些行,只需遍历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.