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。