简体   繁体   中英

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:

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))

If you want to work on the lines just iterate over the islice object:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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