切片可理解为更高级别的索引。基础的部分就简单描述一下。通常一个切片操作要提供三个参数 [start_index: stop_index: step]
- start_index是切片的起始位置
- stop_index是切片的结束位置(不包括)
- step可以不提供,默认值是1
一、概念
alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
alist[0] #0
alist[0:1] #0
alist[1:5] #[1, 2, 3, 4]
二、高级操作
2.1、islice
def count(n):
while True:
yield n
n += 1
c = count(0)
import itertools
for x in itertools.islice(c, 7, 8): # 这个切片是不可逆的,他会丢掉迭代后的元素
print(f'iter val is: {x}') #iter val is: 7
2.2、dropwhile
"""跳过可迭代部分开始的元素,下例是去掉注释部分,如果明确了需要跳过的部分,也可以用切片"""
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line: line.startswith('#'), f):
print(f'{line}', end='')
2.3、permutations, combinations, combinations_with_replacement
"""组合迭代,输出所有元素的不同排序"""
item_list = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(item_list):
print(f'all permutations is: {p}')
#all permutations is: ('a', 'b', 'c')
"""组合迭代,每次输出2个元素的不同排序"""
for p in permutations(item_list, 2):
print(f'permutations 2 is: {p}')
#permutations 2 is: ('a', 'b')
"""组合迭代,按顺序只输出一次所有元素的排序"""
from itertools import combinations
for c in combinations(item_list, 3):
print(f'combinations 3 is: {c}')
#combinations 3 is: ('a', 'b', 'c')
"""组合迭代,每次输出2个元素的不同排序"""
for c in combinations(item_list, 2):
print(f'combinations 2 is: {c}')
# combinations 2 is: ('a', 'b')
"""这个函数和上面函数的区别是,上面的combinations一旦一个元素完成遍历就会从组合中去掉"""
from itertools import combinations_with_replacement
for c in combinations_with_replacement(item_list, 3):
print(f'combinations with replacement is: {c}')
# combinations with replacement is: ('a', 'a', 'a')
2.4、chain, merge
#集合迭代
from itertools import chain
a_list = [1, 3, 5, 7]
b_list = ['hello', 'world', 'nice']
for x in chain(a_list, b_list):
print(f'chain result: {x}')
#顺序迭代
import heapq
a_list = [1, 3, 5, 9]
b_list = [2, 4, 6, 10]
for c in heapq.merge(a_list, b_list):
print(f'order result: {c}')
2.5、zip
xpt_list = [21, 35, 6, 28, 37, 19]
ypt_list = [11, 8, 3, 5, 2, 9]
for x, y in zip(xpt_list, ypt_list):
print(f'xpt_list element: {x}, ypt_list element: {y}')
"""====同时迭代多个序列===="""
a_list = [3, 7, 11]
b_list = ['hello', 'world', 'python', 'good']
"""如果多个序列长度不一致,则取最短的长度"""
for i in zip(a_list, b_list):
print(f'zip result: {i}')
"""这个函数会取最长的长度,不足的地方显示None"""
from itertools import zip_longest
for i in zip_longest(a_list, b_list):
print(f'zip longest result: {i}')
"""不足的地方可以指定填充值"""
for i in zip_longest(a_list, b_list, fillvalue=0):
print(f'zip longest fill value 0: {i}')
header_list = ['name', 'course', 'score']
value_list = ['python', 20, 0.3]
"""打包成一个字典或一个列表"""
s = dict(zip(header_list, value_list))
b = list(zip(a_list, b_list))