Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 设置函数以接受startIndex:stopIndex形式的参数_Python_List_Python 3.x - Fatal编程技术网

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

Python 设置函数以接受startIndex:stopIndex形式的参数,python,list,python-3.x,Python,List,Python 3.x,例如: 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 = ind

例如:

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“。连接(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

它起作用了,似乎您还必须首先将它们转换为整数,否则python会认为它们是浮点。谢谢!谢谢你的提示,但我已经有了一个编码函数,我只是想知道如何在start和stop之间更改所需的参数:stop。