python : itertools 中的 islice : 获取迭代器结果的切片,消耗迭代器

islice(iterable, [start, ] stop [, step]):
创建一个迭代器,生成项的方式类似于切片返回值: iterable[start : stop : step],将跳过前start个项,迭代在stop所指定的位置停止,step指定用于跳过项的步幅。与切片不同,负值不会用于任何start,stop和step,如果省略了start,迭代将从0开始,如果省略了step,步幅将采用1.https://blog.csdn.net/larykaiy/article/details/82934527
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

示例:

step1:创建文本文档

my_file.txt

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 wzg16 <wzg16@wzg16-linux>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
step2:读取文档前三行

read1.py


with open("my_file.txt") as f:
lines = f.readlines()
print(lines[0:3])

"""
返回:
['#!/usr/bin/env python\n', '# -*- coding: utf-8 -*-\n', '#\n']
"""
read_islice.py

from itertools import islice


with open("my_files.txt") as f2:
for i in islice(f2,0,3):
print(i)
result = islice(f2,0,3)
print(result)
print(list(result))

"""
输出:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
<itertools.islice object at 0x7f52a94dedb8>
['# Copyright 2019 wzg16 <wzg16@wzg16-linux>\n', '# \n', '# This program is free software; you can redistribute it and/or modify\n']
"""
islice 会消耗迭代器:

示例:

from itertools import islice

l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
it = iter(l)

slice1 = islice(it,0,3)
slice2 = islice(it,0,3)
slice3 = islice(it,3,6)
slice4 = islice(it,0,3)

print("slice1 = ",list(slice1))
print("slice2 = ",list(slice2))
print("slice3 = ",list(slice3))
print("slice4 = ",list(slice4))

"""
输出:
slice1 = [1, 2, 3]
slice2 = [4, 5, 6]
slice3 = [10, 11, 12]
slice4 = [13, 14, 15]

————————————————
版权声明:本文为CSDN博主「wzg2016」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/strive_for_future/article/details/95388081

posted on 2021-06-03 20:33  ExplorerMan  阅读(253)  评论(0编辑  收藏  举报

导航